#SingleInstance, Force
DetectHiddenWindows,On
IfNotExist,lib
FileCreateDir,lib
IfExist,settings.xml
FileMove,settings.xml,lib\settings.xml
comm:=new xml("commands"),settings:=new xml("settings","","lib\settings.xml"),files:=new xml("files"),positions:=new xml("positions"),version:=new xml("version")
global comm,positions,settings,files
filecheck(),Gui(),scin:=sci.hw.sc
global scin
return
add:
return
class sci{
	hw:=[],lc:=""
	__New(hwnd,ref,x=0,y=0,w=500,h=500){
		Static ScintillaIndex:=0
		if !DllCall("GetModuleHandle","str","SciLexer.dll")
		DllCall("LoadLibrary","str","SciLexer.dll")
		this.hwnd:=DllCall("CreateWindowEx" ,"int",0x200 ,"str","Scintilla"
		,"str","Scintilla" . ++ScintillaIndex ,"int", 0x52310000
		,"int",X ,"int",Y ,"int",W ,"int",H ,"uint",hwnd,"uint",0 ,"uint",0 ,"uint",0)
		for a,b in {fn:2184,ptr:2185}
		this[a]:=DllCall("SendMessageA","UInt",this.hwnd,"int",b,int,0,int,0)
		this.ref:=ref
		sci.hw[ref]:=this,sci.hw[this.hwnd]:=this
	}
	main(x=0){
		if !x
		return files.ssn("//*[@sc='" sci.lc.2357 "']../@main").text
		return files.ssn("//*[@sc='" sci.lc.2357 "']..")
	}
	getseltext(){
		f:=sci.lc
		VarSetCapacity(text,f.2161),f.2161(f.2161,&text)
		return strget(&text,f.2161,utf-16)
	}
	string(x*){
		for a,sc in sci.hw{
			for a,b in x
			sc[b.1](b.2,b.3)
		}
	}
	__Call(a="",b=0,c=0,d=0){
		f:=this
		if (a="textrange"){
			VarSetCapacity(text,abs(b-c)),VarSetCapacity(textrange,12,0),NumPut(b,textrange,0,"UInt"),NumPut(c,textrange,4,"UInt"),NumPut(&text,textrange,8,"UInt")
			f.2162(0,&textrange)
			rv:=strget(&text,abs(b-c),"cp0")
			return rv
		}
		if (a="gettext"){
			VarSetCapacity(text,f.2182),f.2182(f.2182,&text)
			return strget(&text,length,utf-16)
		}
		if (a="loop"){
			lp:=(c+1)!=""?"Int":"AStr",wp:=(d+1)!=""?"Int":"AStr"
			return DllCall(this.fn,"Ptr",this.ptr,"UInt",b,lp,c,wp,d,"Cdecl")
		}
		if !a
		return m("Issue")
		lp:=(b+0)!=""?"Int":"AStr",wp:=(c+0)!=""?"Int":"AStr"
		if IsObject(c)
		c:=c.1,wp:="Astr"
		return DllCall(this.fn,"Ptr",this.ptr,"UInt",a,lp,b,wp,c,"Cdecl")
	}
	__Get(a*){
		return DllCall(this.fn,"Ptr",this.ptr,"UInt",a.1,"Int",0,"Int",0,"Cdecl")
	}
	set(){
		for a,sc in sci.hw{
			if !(a+0)
			continue
			indent:=settings.ssn("//Indent").text
			indent:=indent?indent:5
			sc.2124(1),sc.2036(indent),sc.4006(0,"asm")
			loop,10
			if keywords(A_Index)
			sc.4005(A_Index-1,keywords(A_Index))
			sc.2051(6,0xff0000)
			sc.2077(0,"#abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVXWYZ")
			;sc.2443(0,chr(9) chr(32))
		}
	}
}
notify(a,b,c,d){
	Critical
	if A_Gui not in 1,9
	return
	static dupsel
	control:=NumGet(b+0)
	if !s:=sci.hw[control]
	return
	sci.lc:=s
	code:=NumGet(b+8),cp:=s.2008,scpos:=NumGet(b+12)
	if (code=2007){
		WinGetActiveStats,t,w,h,x,y
		info:=win.posinfo()
		if (t!="Quick Find"){
			if (info.start!=info.end)
			highlight(info.start,info.end),dupsel:=1
			else if dupsel
			s.2500(1),s.2504(1,0),s.2505(0,s.2006),dupsel:=0
		}
		bm:=s.2353(cp-1,0)
		if bm!=-1
		s.2351(cp-1,bm)
		if bm=-1
		s.2351(-1,-1)
		SB_SetText("Position: " cp " Column: " s.2129(cp),1)
		if !settings.ssn("//Show_Selected_Duplicates").Text
		return
	}
	if (code=2001){
		char:=NumGet(b+16)
		if char in 13,10
		return
		word:=s.textrange(s.2266(cp,1),s.2267(cp,1))
		if (StrLen(word)>1&&s.2102=0){
			keywords:=keywords(SubStr(word,1,1))
			loop,parse,keywords,%a_space%
			if RegExMatch(A_LoopField,"Ai)" word)
			list.=a_loopfield " "
			sort,list,UD%A_Space%
			if list
			s.2100(strlen(word),trim(list))
		}
		if char
		SB_SetText("Last Character Added=" Chr(char) " Code=" char,3)
		if char=125
		fix_indent()
		if char in 44,32
		replace(),context(char)
	}
	if (code=2022){
		SetTimer,ss,1
		return
	}
	if (code=2008){
		qu:=NumGet(b+28)
		char:=NumGet(b+36)
		if (char>0 && char<1000){
			fn:=files.ssn("//*[@sc='" s.2357 "']/@file").text,update({fn:fn})
			SetTimer,indent,1
			return
		}
		edited:=NumGet(b+24)
		if (edited&0x01)||(edited&0x02)
		fn:=files.ssn("//*[@sc='" s.2357 "']/@file").text,update({fn:fn})
	}
	if (code=2027){
		Down:=NumGet(b+20)=2
		style:=s.2010(s.2008),value:=down?"Background":"Color"
		for a,b in {1:style,2:32}{
			color:=settings.ssn("//Style" b "/@" value).Text
			if (Color!="")
			break
		}
		new:=dlg_color(color)
		if new=""
		return
		if new!=""
		obj:=down?{Background:new}:{Color:new},settings.add("Gui/Fonts/Style" style,obj),setcolor()
	}
	if (code=2010){
		margin:=NumGet(b+64),mod:=NumGet(b+20)
		if (margin=0){
			bc:=mod=2?"Background":"Color"
			color:=dlg_color(settings.ssn("//Style33/@" bc).Text)
			if color=""
			return
			c:=settings.ssn("//Style33/@" bc),c.text:=color,setcolor()
		}
		if margin=2
		s.2231(s.2166(scpos))
	}
	if (code=2016){
		if !s.2230(s.2166(scpos)){
			line:=s.2166(scpos),level:=s.2223(line),end:=s.2224(line,level)
			text:=s.textrange(s.2136(line)+2,s.2136(end))
			show:=SubStr(text,1,500)
			show.=StrLen(text)>500?"`n...":""
			s.2205(0xAAAAAA),s.2206(0x0)
			s.2200(s.2128(line),show)
		}
	}
	if (code=2017)
	s.2201
}
ss:
SetTimer,ss,Off
context()
return
in(){
	indent:
	s:=sci.lc,pos:=win.posinfo()
	s.2078
	SetTimer,indent,Off
	fix_indent(),ind:=s.2128(s.2166(s.2008))
	ind:=s.2127(s.2166(s.2008))
	if (pos.start=pos.end)
	if ind
	Send,^{Right}
	s.2079
	return
}
class rebar{
	__New(hgui){
		hRebar:=DllCall("CreateWindowEx","uint",0,"str","ReBarWindow32","uint",0,"uint",1442842624|0x8000,"uint",x,"uint",y,"uint",w,"uint",h,"uint",hGui,"uint",MODULEID,"uint",0,"uint",0,"Uint")
		rebar.hrebar(hrebar),this.hrebar:=hrebar
	}
	Insert(hCtrl){
		pos:=Rebar.compileBand(BAND,hCtrl)
		SendMessage,A_IsUnicode?0x40A:0x401,pos,&BAND,,% "ahk_id" this.hRebar
		ifEqual,ErrorLevel,0,return0
		return NumGet(BAND,52)
	}
	hrebar(bar=""){
		static rebar
		if bar
		return rebar:=bar
		return rebar
	}
	SetLayout(hRebar,Layout){
		if !(hrebar&&this.hrebar)
		hrebar:=rebar.hrebar()
		if !hrebar
		hrebar:=this.hrebar
		for a,b in layout
		pos:=Rebar.ID2Index(hRebar,b.1),Rebar.SetBandWidth(hRebar,pos,b.2)
	}
	GetBand(hRebar,WhichBand,ByRef b,ByRef l,ByRef n){
		hmask:=335
		whichband--
		VarSetCapacity(BAND,80,0),NumPut(80,BAND),NumPut(hMask,BAND,4),VarSetCapacity(wTxt,64),NumPut(&wTxt,BAND,20),NumPut(64,BAND,24)
		SendMessage,0x405,WhichBand,&BAND,,ahk_id %hRebar%
		L:=NumGet(BAND,44)
		N:=NumGet(BAND,52)
		b:=10000+whichband+1
		return
	}
	GetLayout(ByRef ll){
		hrebar:=rebar.hrebar(),layout:=[]
		loop, % ReBar.Count(hRebar)
		rebar.GetBand(hRebar,A_Index,b,n,l),layout.Insert([b,n,l]),ll.=n ","
		ll:=Trim(ll,",")
		return layout
	}
	Count(hRebar){
		return DllCall("SendMessageA","Uint",hrebar,"int",0x40c)
	}
	ID2Index(hRebar,Id){
		SendMessage,0x410,Id,,,ahk_id %hRebar%
		return Errorlevel+1
	}
	SetBand(hRebar, WhichBand){
		WhichBand := WhichBand > 10000 ? Rebar.Id2Index(hrebar, WhichBand)-1 : WhichBand-1
		p:=Rebar.compileBand(BAND,0)
		return DllCall("SendMessageA","Uint",hrebar,"int",0x406,"int",whichband,"int",&band)
	}
	SetBandWidth(hRebar, WhichBand, Width){
		WhichBand:=WhichBand>10000?Rebar.Id2Index(hrebar,WhichBand)-1:WhichBand-1
		VarSetCapacity(BAND,80),NumPut(80,BAND),NumPut(0x40,BAND,4),NumPut(Width,BAND,44)
		SendMessage,0x406,WhichBand,&BAND,,ahk_id%hRebar%
		return ErrorLevel
	}
	compileBand(ByRef BAND, hCtrl){
		static id=10000, NP_T
		ControlGetPos,,,wIdeal,,, ahk_id %hCtrl%
		hwnd:=WinExist()
		VarSetCapacity(size,16,0),DllCall("user32\GetClientRect","uint",hwnd,"uint",&size),w:=NumGet(size,8),maxh:=NumGet(size,12)
		ControlGetPos,,,,h,msctls_statusbar321
		h:=maxh-h-3,NP_L:=(NP_L+0!="")?NP_L:wIdeal+10,hmask:=((hctrl?848:0)|(h?32:0)),id+=hCtrl?1:0
		VarSetCapacity(BAND, 80, 0),NumPut(80,BAND),NumPut(hMask,BAND, 4),NumPut(hCtrl	,BAND, 32),NumPut(NP_mW,BAND, 36)
		,NumPut(h,BAND,40),NumPut(NP_L,BAND,44),NumPut(id,BAND,52),NumPut(wIdeal,BAND,68),NumPut(lparam,BAND,72)
		return (NP_P+0 != "") ? NP_P-1 : -1
	}
	guisize(){
		GuiSize:
		hrebar:=rebar.hrebar()
		lay:=rebar.getlayout(x)
		width:=a_guiwidth-lay.3.2-lay.1.2
		Rebar.SetBand(hRebar,1)
		Rebar.SetBandWidth(hRebar,10002,width)
		return
	}
}
Gui(){
	Gui,+hwndhwnd +Resize
	sc:=new sci(hwnd,"sc",0,0,100,100)
	sc1:=new sci(hwnd,"sc1",0,0,100,100)
	sc1.2181(0,"Click here and then click on an open file in the left pane")
	value=1
	hrebar:=new rebar(hwnd),keywords(98),s:=settings,w:=s.ssn("//window1/position"),pos:=[],bar:=ssn(w,"@bar").text,win.h(1,hwnd)
	loop,Parse,bar,`,
	pos.insert([1000 A_Index,A_LoopField])
	Gui,Add,StatusBar
	SB_SetParts(200,200,250,200)
	setcolor(),ImageListID := IL_Create(2)
	for a,b in [7,71]
	IL_Add(ImageListID,"shell32.dll",b)
	Gui,Add,TreeView,hwndtv gfe AltSubmit ImageList%ImageListID%
	;Gui,Add,TreeView,hwndtv1
	var({tree:tv1})
	for a,b in ["File Explorer","Open or create a new file"]
	TV_Add(b)
	sci.string([2040,25,13],[2040,26,15],[2040,27,11],[2040,28,10],[2040,29,9],[2040,30,12],[2040,31,14])
	sci.string([2244,2,0xFE000000],[2242,0,0],[2242,2,13],[2460,3],[2462,1],[2134,1],[2260,1],[2246,2,1],[2115,1],[2242,1,0])
	sci.string([2233,16],[2155,0,0],[2132,1],[2264,1000],[2037,65001],[2040,1,7],[2634,1])
	sc.2521(1)
	sc.2242(3,12)
	sc.2115(1),sc1.2115(1)
	zoom:=settings.ssn("//zoom").text
	zoom:=zoom?zoom:1
	sc.2373(zoom)
	OnMessage(0x4E,"Notify"),OnMessage(5,"setguipos"),OnMessage(0x232,"sizemove"),OnMessage(0x06,"Focus")
	OnMessage(0x10,"Destory")
	hrebar.insert(tv),hrebar.insert(sc.hwnd),hrebar.insert(sc1.hwnd) ; ,hrebar.insert(tv1) ,sci.set()
	for a,b in xml.easyatt(w)
	if a in x,y,w,h
	if b
	position.=a b " "
	position:=position?position:"w890 h500"
	menu()
	if settings.ssn("//lastopen")
	autoopen([1])
	max:=settings.ssn("//Gui/window1/position/@max").Text
	max:=max?"Maximize":""
	Gui,1:Show,% position " " max
	lastopen:=settings.ssn("//lastopen/@file").text
	sci.string([2040,25,13],[2040,26,15],[2040,27,11],[2040,28,10],[2040,29,9],[2040,30,12],[2040,31,14],[2614,1])
	sc.2563(1),sc.2565(1),sc.2614(1),sc.2608(1)
	sc.2614(1),sc.2422(2),sc.2400
	if pos.1.1
	hrebar.setlayout(0,pos)
	setpos(),hotkeymenu(),hotkeys(1)
	WinSet,Redraw
	hotkey({"[":{brace:1},"{":{brace:1},"(":{brace:1},"+^up":{moveline:1},"+^down":{moveline:1},"^!up":{selabove:1},"^!down":{selabove:1}})
	size:=settings.ssn("//Style5/@size").text?5:32
	sc.2242(0,sc.2276(size,[sc.2154 1]))
	sci.lc:=sc
	sc.2400
	if !settings.ssn("//lastopen/file").text
	{
		sc.2181(0,"Please open a file or start a new one")
		sc.2171(1)
		setcolor()
		Return
	}
	select_file(lastopen)
	Return
	GuiClose:
	save(),Exit()
	Return
}
class xml{
	__New(param*){
		ref:=param.1,root:=param.2,file:=param.3
		file:=file?file:ref ".xml",root:=!root?ref:root
		temp:=ComObjCreate("MSXML2.DOMDocument"),temp.setProperty("SelectionLanguage","XPath")
		ifexist %file%
		temp.load(file),this.xml:=temp
		else
		this.xml:=xml.CreateElement(temp,root)
		this.file:=file
		xml.xk({ref:ref,obj:this})
	}
	xk(xml=""){
		static list:=[]
		if IsObject(xml)
		return list[xml.ref]:=xml.obj
		if !xml
		return list
		if list[xml]
		return list[xml]
	}
	__Get(x=""){
		return this.xml.xml
	}
	CreateElement(doc,root){
		x:=doc.CreateElement(root),doc.AppendChild(x)
		return doc
	}
	add(path="",att="",text="",dup="",find="",under=""){
		main:=this.xml.SelectSingleNode("*")
		for a,b in find
		if found:=main.SelectSingleNode("//" path "[@" a "='" b "']"){
			for a,b in att
			found.setattribute(a,b)
			found.text:=text
			return found
		}
		if under
		{
			p:=under
			new:=this.xml.CreateElement(path),p.AppendChild(new)
			for a,b in att
			new.SetAttribute(a,b)
			if !(text="")
			new.text:=text
			return new
		}
		if p:=this.xml.SelectSingleNode(path)
		for a,b in att
		p.SetAttribute(a,b)
		else
		{
			p:=main
			Loop,Parse,path,/
			{
				total.=A_LoopField "/"
				if dup
				new:=this.xml.CreateElement(A_LoopField),p.AppendChild(new)
				else if !new:=p.SelectSingleNode("//" Trim(total,"/"))
				new:=this.xml.CreateElement(A_LoopField),p.AppendChild(new)
				p:=new
			}
			for a,b in att
			p.SetAttribute(a,b)
			if Text!=""
			p.text:=text
		}
		return p
	}
	remove(){
		this.xml:=""
	}
	save(){
		this.xml.transformNodeToObject(xml.style(),this.xml)
		this.xml.save(this.file)
	}
	transform(){
		this.xml.transformNodeToObject(xml.style(),this.xml)
	}
	ssn(node){
		return this.xml.SelectSingleNode(node)
	}
	sn(node){
		return this.xml.SelectNodes(node)
	}
	style(){
		static
		if !IsObject(xsl){
			xsl:=ComObjCreate("MSXML2.DOMDocument")
			style=
			(
			<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
			<xsl:output method="xml" indent="yes" encoding="UTF-8"/>
			<xsl:template match="@*|node()">
			<xsl:copy>
			<xsl:apply-templates select="@*|node()"/>
			<xsl:for-each select="@*">
			<xsl:text></xsl:text>
			</xsl:for-each>
			</xsl:copy>
			</xsl:template>
			</xsl:stylesheet>
			)
			xsl.loadXML(style), style:=null
		}
		return xsl
	}
	easyatt(node,notext=""){
		list:=[],nodes:=sn(node,"@*")
		while,n:=nodes.item[A_Index-1]
		list[n.nodename]:=n.text
		if !notext
		list[1]:=node.text
		return list
	}
}
ssn(node,path){
	return node.SelectSingleNode(path)
}
sn(node,path){
	return node.SelectNodes(path)
}
testing(){
}
highlight(start,end){
	static lastfind,create
	s:=sci.lc
	find:=s.textrange(start,end)
	if (find=lastfind)
	return
	s.2500(1),s.2504(1,1),s.2505(1,s.2006)
	s.2080(1,8)
	create:=1
	s.2523(1,110)
	color:=settings.ssn("//Gui/Fonts/Stylessd/@Color").Text
	color:=color?color:0xff0000
	s.2082(1,color)
	highlt(find),lastfind:=find
}
highlt(find){
	s:=sci.lc
	s.2500(1),out:=s.gettext(),found:=1,findreg:="\Q" find "\E"
	case:=window({get:17}).case?"":"i"
	while found:=RegExMatch(out,"O" case ")" findreg,fo,found){
		if sel.sel
		if (found+fo.len()-1>sel.oe)
		break
		s.2504(fo.pos()-1,strlen(find)),found+=fo.len()
		if !fo.len()
		break
		count:=A_Index
	}
	if count=1
	s.2500(1),s.2504(1,0),s.2505(0,s.2006),dupsel:=0
}
Locked_Scroll_Down(){
	for a,b in sci.hw
	b.2342
}
Locked_Scroll_Up(){
	for a,b in sci.hw
	b.2343
}
keywords(x=""){
	static
	if (!isobject(keywords) || x=98){
		c:=comm
		keywords:=[],com:=[],list:="",keyword:=[],personal:=""
		items:=c.ssn("//Items").Text
		context:=c.ssn("//Commands/Commands").text
		personal:=settings.ssn("//Variables").text
		for a,b in ["context","items","personal"]{
			StringLower,h%b%,%b%
			h%b%:=RegExReplace(h%b%,"[^0-9a-zA-Z _]")
		}
		sort,hitems,UD%A_Space%
		sort,hcontext,UD%A_Space%
		sort,hpersonal,UD%A_Space%
		keywords[1]:=hcontext,keywords[2]:=hitems,keywords[3]:=hpersonal
		loop,7
		{
			keywords[a_index+3]:=settings.ssn("//Gui/Fonts/Keywords/Keyword_List_" A_Index).text
			keywords[1]:=regexreplace(keywords[1],regexreplace(keywords[a_index+3]," ","\b|\b"))
			keywords[2]:=regexreplace(keywords[2],regexreplace(keywords[a_index+3]," ","\b|\b"))
		}
		alpha:=[]
		c:=c.ssn("//Controls").text
		total:=context " " items " " personal " " c
		Sort,total,UD%A_Space%
		Loop,Parse,total,%A_Space%,%A_Space%
		{
			f:=SubStr(A_LoopField,1,1)
			alpha[substr(a_loopfield,1,1)]:=1
			%f%.=a_loopfield " "
			keywords[substr(a_loopfield,1,1)].=a_loopfield " "
		}
		sort,list,UD%A_Space%
		keywords[99]:=total
		Loop,Parse,total,%A_Space%
		keyword[A_LoopField]:=A_LoopField
	}
	if !x
	return keyword
	out:=keywords[x]
	sort,out,D%a_space%
	return out
}
class win{
	pos(){
		static
		if !IsObject(pos){
			SysGet,border,32
			SysGet,caption,4
			SysGet,men,55
			pos:={border:border,caption:caption,status:h,ymin:caption+Border,menu:men+1}
		}
		return pos
	}
	getwinpos(ByRef x,ByRef y,ByRef w,ByRef h,wn){
		WinGetPos,x,y,,,ahk_id %wn%
		VarSetCapacity(size,16,0),DllCall("user32\GetClientRect","uint",wn,"uint",&size),w:=NumGet(size,8),h:=NumGet(size,12)
		pos="x" x " y" y " w" w " h" h
		WinGet,max,MinMax,% "ahk_id" wn
		out:=max?"Maximize":pos
		return out
	}
	h(num="",val=""){
		static hwnd:=[]
		if !num
		return hwnd
		if IsObject(num)
		return hwnd["h" num.1]
		if !val
		return hwnd[num]
		hwnd[num]:=val,hwnd["h" num]:="ahk_id " val
	}
	posinfo(){
		s:=sci.lc
		current:=s.2008
		line:=s.2166(current),se:=[]
		ind:=s.2128(line)
		lineend:=s.2136(line)
		se[current]:=1,se[s.2009]:=1
		out:={current:current,line:line,ind:ind,lineend:lineend,start:se.minindex(),end:se.maxindex()}
		return out
	}
}
setcolor(){
	s:=settings,Default:=[]
	if !s.ssn("//Gui/Fonts").xml
	defaultfonts()
	for a,sc in sci.hw{
		if a is number
		continue
		nodes:=s.sn("//Gui/Fonts/*")
		list:={Font:2056,Size:2055,Color:2051,Background:2052,Bold:2053,Italic:2054,Underline:2059}
		style5:=xml.easyatt(s.ssn("//Style5")),default:=xml.easyatt(s.ssn("//Style32"))
		for a,b in style5
		default[a]:=b
		for a,b in List
		sc[b](32,value:=default[a]?default[a]:0)
		sc.2069(0xffffff),sc.2050,sc.2242(0,35),sc.2055(32,10)
		while,fnt:=nodes.item[count:=A_Index-1]
		for a,b in xml.easyatt(fnt){
			if (b!=""){
				if !number:=RegExReplace(fnt.nodename,"[^0-9]")
				continue
				sc[list[a]](number,b)
				if (number=33 && a="Background")
				sc.2290(1,b),sc.2291(1,b)
				if number > 1000
				sc[number](b)
			}
		}
		Default["flash"]:=1
		colors(default)
		for a,b in {Stylessb:[2068,1],Stylewwmc:[2051,32]}
		if color:=settings.ssn("//" a "/@Color").Text
		sc[b.1](b.2,color)
		color:=settings.ssn("//Stylemsc/@Color").Text
		color:=color?color:0xff0000
		sc.2601(color),setcolors:=1
		xx:=xml.easyatt(settings.ssn("//Gui/Fonts/Button/State0"))
		button.colors(0,xx.background?xx.background:Default.Background,xx.border?xx.border:Default.Color,xx.text?xx.text:Default.Color)
		xx:=xml.easyatt(settings.ssn("//Gui/Fonts/Button/State1"))
		Button.colors(1,xx.Background?xx.Background:0xFFFFFF,xx.Border?xx.Border:0,xx.text?xx.text:0)
	}
}	
colors(Default=""){
	static D
	if IsObject(default)
	D:=Default
	if default=Get
	return d
	for a,b in D
	%a%:=b
	for a,b in {bold:bold,italic:italic,underline:underline}
	style.=b?a " ":""
	size:=size<10?10:size
	style.=" s" size
	Background:=RGB(Background)
	for a,b in win.h(){
		if !(a+1)
		continue
		Gui,%a%:Default
		Gui,%a%:font
		gui,%a%:font,% style " c" RGB(Color),%font%
		if a!=1
		gui,%a%:color,%background%,%background%
		winget,controllist,ControlList,% "ahk_id " b
		loop,Parse,ControlList,`n
		{
			guicontrol,+background%background%,%A_LoopField%
			if (a=17&&A_LoopField!="SysTreeView321")
			gui,%a%:font,% s10 " c" RGB(Color),%font%
			guicontrol,font,%A_LoopField%
		}
	}
}
rgb(c){
	setformat,IntegerFast,H
	c:=(c&255)<<16|(c&65280)|(c>>16)
	SetFormat, integerfast,D
	return c
}
defaultfonts(){
	s:=settings
	for a,b in {11:{Color:0xFF0000},12:{Color:0x0000FF},13:{Color:0x00FF00},32:{Color:0x808000,Size:10,Font:"Tahoma",Background:0},33:{Color:0,Background:0xff0000}}
	s.add("Gui/Fonts/Style" a,b)
	s.transform(),s.save()
}
Menu(){
	Menu,o,UseErrorLevel,On
	Menu:=constants("Menu")
	x:=settings
	if !x.ssn("//quick_settings")
	for a,b in Menu{
		item:=clean(b.item)
		if b.Menu="o"{
			if item not in end_of_line,debug,settings
			s=1
			else
			s=0
			x.add("quick_settings/" item,0,s)
		}
	}
	for a in Menu{
		Menu,% Menu[a].Menu,add,% Menu[a].item,Menu
		item:=clean(Menu[a].item)
		if x.ssn("//quick_settings/" item).Text&&item!="settings"{
			%item%()
			Menu,% Menu[a].Menu,ToggleCheck,% Menu[a].item
		}
		if IsFunc(item)=0
		if Menu[a].Menu!="o"
		Menu,% Menu[a].Menu,Disable,% Menu[a].item
	}
	
	code_vault(1)
	Menu,bar,Add,&File,:f
	Menu,bar,Add,&Edit,:e
	Menu,bar,Add,&Options,:o
	Menu,bar,Add,&Window,:w
	Menu,bar,Add,&Tools,:t
	Menu,bar,Add,He&lp,:a
	Menu,bar,Add,&Code Vault,:c
	gui,1:Menu,bar
	return
	Menu:
	m:=clean(A_ThisMenuItem)
	if (A_ThisMenu="o" && m="settings")
	return settings()
	if A_ThisMenu=o
	toggle(m,A_ThisMenuItem)
	else
	%m%()
	return
	jumpfile:
	q:=RegExReplace(A_ThisMenuItem,"U)(.* )","","",1)
	main:=positions.ssn("//*[@main='" q "']/@segment").Text
	sel:=main?main:q
	select_file(sel)
	return
}
clean(x,y=0){
	if y=1
	return regexreplace(regexreplace(x," ","_"),"i)(?:[^a-z0-9_]|\&)","")
	if y=2
	return regexreplace(x,"i)(?:[^a-z0-9 ]|\&)","")
	return regexreplace(regexreplace(x,"i)(?:[^a-z0-9 ]|\&)","")," ","_")
}
toggle(m,i){
	x:=settings
	s:=x.ssn("//" m)
	if !s
	s:=x.add("quick_settings/" m)
	if (m="Virtual_Space")
	s.text:=s.text=2?0:2
	else
	s.text:=s.text=1?0:1
	Menu,o,ToggleCheck,%i%
	if IsFunc(m)
	%m%()
}
word_wrap(){
	for a,b in sci.hw
	b.2268(settings.ssn("//Word_Wrap").Text)
}
end_of_line(){
	for a,b in sci.hw
	b.2356(settings.ssn("//End_of_line").Text)
}
virtual_space(){
	scin.2596(settings.ssn("//Virtual_Space").Text)
}
constants(x){
	static hotkeys:={"Remove Spaces From Selected":1,"Toggle Comment Line":1,"Show Scintilla Code in Line":1,"Scintilla Code Lookup":1,"Add variable":1,Run:1,"Insert Function":1,Find:1,Testing:1,"Character Count":1,"Scintilla Code Lookup":1,"Jump to Segment":1,"Show Functions":1,"Delete Line":1,"Copy Line":1,"Quick Find":1,"Locked Scroll Down":1,"Locked Scroll Up":1,"Select Matching Brace":1,"Create Comment Block":1,headderval:{1:"Value",2:"Hotkey",3:"Window"}}
	static menu:="f,&New|f,&Open|f,I&mport|f,&Close|f,New S&egment|f,Create Se&gment From Selection|f,&Save|f,Open Fol&der|f,&Run|f,Run Se&lected Text|f,&Version|f,&Full Backup|f,&Publish|f,&Auto Update|f,&Upload|f,Expor&t|e,The&me|e,Fi&x Indentation|e,R&eplace Text|e,&Find|e,Fin&d in Segment|e,Ed&it Replacements|e,Cu&t|e,Edit &Highlight Text|e,&Copy|e,&Jump to Segment|e,Paste	Ctrl &V|e,&Restore|e,Remove Current &Segment|e,Insert F&unction|e,Ch&aracter Count|a,&Help|a,&About|w,&Variables|f,C&lean Position Data|f,E&xit|o,&Settings|o,&Auto Fix Indentation|o,&Highlight Matching Brace|o,&Word Wrap|o,&Context Sensitive Help|o,S&imple Brace|o,Smart &Parentheses|o,&End of line|o,&Debug|o,Show Selected Duplicates|o,&Virtual Space|f,Sho&w file|t,MsgBox Creator|t,A&HK Pastebin Code|"
	;f,Export &GIThub|f,Export P&lugin|    e,&Plugins|
	static ftp:={Server:"",Port:1,Username:"",Password:"",headderval:{1:"Value",2:"FTP Settings",3:""}}
	static general:={Indent:1}
	val:=[]
	if x=hotkeys
	{
		for a,b in hotkeys
		val[clean(a,2)]:=1
		loop,parse,menu,|
		{
			StringSplit,_,A_LoopField,`,
			if _1 in f,e
			val[clean(_2,2)]:=_1
		}
		return val
	}
	if isobject(%x%)
	return out:=%x%
	loop,parse,%x%,|
	{
		StringSplit,_,A_LoopField,`,
		val[A_Index]:={menu:_1,item:_2}
	}
	return val
}
settings(){
	static
	hotkeys(0)
	Gui,8:Destroy
	Gui,8:+hwnder +Owner1
	win.h(8,er),colors()
	Gui,8:Default
	Gui,Add,Text,section w0
	Gui,Add,Text,xs ys,Click on a value to change it, or press f2.
	Gui,Add,Text,,Make sure to press enter after setting your value`nRight click  an option or press F1 for a hotkey builder
	ControlGetPos,,,,h,Static2,% win.h([8])
	h+=1
	Gui,Add,Tab,vstab h10 gsetpop Buttons,Hotkeys|General
	Gui,Tab
	Gui,Add,ListView,w500 h500 Section -Multi gslv AltSubmit -ReadOnly,Hotkey|Action
	all:=xml.easyatt(settings.ssn("//Ftp"))
	Gui,Add,GroupBox,w500 r5 Section,FTP Settings
	for a,b in ["Server","Port","Username","Password"]{
		pass:=A_Index=4?"password":""
		if A_Index=1
		Gui,Add,Text,xs+10 ys+%h% section,%b%:
		else
		Gui,Add,Text,xs section,%b%:
		Gui,Add,Edit,x+10 ys w300 v%b% %pass%,% all[b]
	}
	Gui,Show,,Settings
	ControlFocus,SysListView321
	setpop:
	Gui,8:Submit,nohide
	Gui,8:Default
	LV_Delete()
	for a,b in constants(stab){
		if isobject(b)
		for index,value in b
		lv_modifycol(index,"",value)
		else
		LV_Add("",settings.ssn("//" clean(a)).Text,a)
	}
	LV_ModifyCol(1,"AutoHDR"),LV_Modify(1,"select focus")
	GuiControl,,Static1,%out%
	Gui,Show,,Settings
	ControlFocus,SysListView321,% win.h([8])
	Hotkey({f1:{settingf1:8}})
	Button.Redraw()
	return
	slv:
	Gui,8:Submit,Nohide
	if A_GuiEvent=i
	{
		LV_GetText(value,LV_GetNext())LV_GetText(setting,LV_GetNext(),2)
		if !value
		remove:=settings.ssn("//" stab "/" clean(setting)),remove.parentnode.removechild(remove)
		else
		settings.add(stab "/" clean(setting),"",value)
	}
	return
	settingf1:
	8GuiContextMenu:
	window({num:99,title:"Hotkey Builder",gui:[["hotkey","vhotkey ghkb limit2"]]
	,GuiSize:{msctls_hotkey321:"w"}})
	Gui,99:Show
	return
	hkb:
	var:=window({get:99})
	Gui,8:Default
	LV_GetText(action,LV_GetNext(),2)
	LV_Modify(LV_GetNext(),"",var.hotkey,action)
	return
	99GuiEscape:
	99GuiClose:
	Hotkey,IfWinActive,% win.h([8])
	Hotkey,f1,settingf1,On
	ControlFocus,SysListView321,% win.h([8])
	Gui,99:Destroy
	return
	8GuiEscape:
	8GuiClose:
	Gui,8:Submit
	settings.add("Ftp",{username:username,password:password,port:port,server:server})
	hotkeys(1),hotkeymenu(),stab:=""
	Gui,8:Destroy
	return
	8GuiSize:
	VarSetCapacity(Rect,16,0)
	SendMessage,0x130a,0,&Rect,SysTabControl321,% win.h([8])
	h:=NumGet(Rect,12,"Int")
	ControlMove,SysTabControl321,,,%A_GuiWidth%,%h%,% win.h([8])
	ControlGetPos,x,y,w,h,SysTabControl321,% win.h([8])
	ControlMove,SysListView321,%x%,% y+h,,,% win.h([8])
	return
	settings:
	settings()
	return
}
all(){
	return {sc:sci.hk(),x:xml.xk()}
}
context(key=""){
	a:=all(),kw:=keywords(),s:=sci.lc,home:=s.2128(s.2166(s.2008)),kc:=keywords("commands")
	x:=xml.xk().commands
	current:=s.2008
	sleep,0
	while current>home,current--{
		Style:=s.2010(current)
		if (s.2007(current)=40&&style=4)
		if kw[word:=s.textrange(s.2266(current-2,1),s.2267(current-2,1))]
		break
		if (s.2007(current)=41&&style=4)
		current:=s.2353(current),current:=s.2266(current-1)-1
	}
	current:=home+1
	style:=s.2010(current+1)
	if (word=""){
		current:=s.2266(current,1)
		w:=word:=s.textrange(current,s.2267(current,1))
		word:=kw[word:=s.textrange(current,s.2267(current,1))]
	}
	word:=clean(word)
	last:=kw[s.textrange(s.2266(s.2008-1,1),s.2267(s.2008-1,1))]
	last:=clean(last)
	if find:=x.ssn("//Context/" word "/list[text()='" last "']/@list").text{
		if s.2007(s.2008-1)!=44
		s.2003(s.2008,","),s.2160(s.2008+1,s.2008+1)
		Sort,find,D%A_Space%
		s.2100(0,find)
	}
	if (s.2102||settings.ssn("//Context_Sensitive_Help").text=0)
	return
	if find:=x.ssn("//Context/*/list[text()='" word "']/@list").text{
		line:=s.textrange(home,s.2008),hits:=x.sn("//Context/" con "/list")
		while,com:=hits.item[A_Index-1],cc:=ssn(com,"@list").Text
		if InStr(line,com.text){
			RegExMatch(line,"i)" RegExReplace(cc," ","|"),find)
			if !InStr(list,com.text)
			list.=com.text ","
			if !InStr(list,find)
			list.=find ","
			if kw[find]
			lastsyntax:=ssn(ssn(com,".."),"syntax[contains(text(),'" kw[find] "')]/@syntax").text
		}
		list.=lastsyntax
	}
	lip:=s.2128(s.2166(s.2008))
	line:=Trim(s.textrange(s.2266(lip),s.2267(lip))),ct:=x.ssn("//Commands/*[text()='" word "']/@syntax").text
	if !(ct||list)
	return
	syntax:=list?list:word ct
	sback:=RegExReplace(syntax,"\(",",",rep,1),current:=s.2007(s.2008)=44?s.2008-1:s.2008
	text:=s.textrange(home,current)
	start:=home,current,count:=0
	while,start<current,start++
	if (s.2010(start)=4&&s.2007(start)=44)
	count++
	if InStr(syntax,"``n")
	StringReplace,syntax,syntax,``n,`n,all
	count:=rep?sback+=1:count
	st:=InStr(sback,",",0,1,count),e:=InStr(sback,",",0,1,count+1)
	e:=e?e:StrLen(sback)
	s.2205(0xAAAAAA),s.2206(0x808080)
	sleep,0
	if syntax
	s.2200(home,syntax)
	if !InStr(syntax,"`n")
	s.2204(st,e)
	if st=0
	s.2207(0x0000FF)
	else
	s.2207(0xFF0000)
}
msgbox_creator(){
	static
	SysGet,border,33
	SysGet,caption,4
	Gui,10:Destroy
	Gui,10:+Owner1 +hwndhwnd +ToolWindow
	win.h(10,hwnd),colors()
	Gui,10:Default
	Gui,Add,Text,,Title
	ControlGetPos,base,,,h,Static1,% win.h([10])
	h+=3
	Gui,Add,Edit,w300 vtitle
	Gui,Add,Text,,Text:
	Gui,Add,Edit,r2 w300 vtext
	Gui,Add,GroupBox,r8 Section,Buttons
	Gui,Add,GroupBox,ys r8,Icons
	list=OK,OK/Cancel,Abort/Retry/Ignore,Yes/No/Cancel,Yes/No,Retry/Cancel,Cancel/Try Again/Continue
	Loop,Parse,list,`,
	if A_Index=1
	Gui,Add,Radio,ys+%h% xs+10 Checked Section,%A_LoopField%
	else
	Gui,Add,Radio,xs,%A_LoopField%
	Gui,Add,Checkbox,,Help Button
	ControlGetPos,,,w,,Button9,% win.h([10])
	w+=20
	GuiControl,10:Move,Button1,w%w%
	ControlGetPos,x,y,,,Button1,% win.h([10])
	w+=x+10
	GuiControl,10:Move,Button2,x%w%
	w+=10,yy:=y-caption+h
	for a,b in [4,3,2,5]
	if A_Index=1
	Gui, Add, Picture,x%w% y%yy% Icon4 Section,%A_WinDir%\system32\user32.dll
	else
	Gui, Add, Picture,Icon%b% ,%A_WinDir%\system32\user32.dll
	Gui,Add,Radio,y+10 Checked vicon1,No Icon
	Gui,Add,Radio,ys+8 xs+40 section vicon2
	Gui,Add,Radio,ys+40 section xs vicon3
	Gui,Add,Radio,ys+40 section xs vicon4
	Gui,Add,Radio,ys+40 xs vicon5
	ControlGetPos,x,,w,,Button11,% win.h([10])
	ww:=w+20
	GuiControl,10:Move,Button2,w%ww%
	ControlGetPos,x,,w,,Button2,% win.h([10])
	nw:=w+x-base
	loop,2
	GuiControl,10:Move,Edit%A_Index%,w%nw%
	x:=nw+base+10
	Gui,Add,GroupBox,ym x%x% Section r4,Modal
	Gui,Add,GroupBox,r1,Default Button
	Gui,Add,GroupBox,r1,Alignment
	Gui,Add,GroupBox,r3,Timeout and Insert
	list=Normal,Task Modal,Always On Top,System Modal
	Loop,Parse,list,`,
	if A_Index=1
	Gui,Add,Radio,xs+10 ys+%h% Checked,%A_LoopField%
	else
	Gui,Add,Radio,,%A_LoopField%
	ControlGetPos,x,y,,,Button17,% win.h([10])
	xx:=x+10,yy:=y-caption+h
	Gui,Add,Radio,y%yy% x%xx% Checked Group,1st
	Gui,Add,Radio,x+10,2nd
	Gui,Add,Radio,x+10,3rd
	ControlGetPos,x,y,,,Button18,% win.h([10])
	xx:=x+10,yy:=y-caption+h
	Gui,Add,Checkbox,y%yy% x%xx%,Right
	Gui,Add,Checkbox,x+10,Reverse
	ControlGetPos,x,y,,,Button19,% win.h([10])
	xx:=x+10,yy:=y-caption+h
	Gui,Add,Text,x%xx% y%yy%,Timeout:
	Gui,Add,Edit,number x+5 vtimeout,1000
	Gui,Add,Button,x+5 gcopy hwndb1,Copy
	Gui,Add,Button,x%xx% y+10 gtest Default hwndb2,Test
	Gui,Add,Button,x+5 ginsert hwndb3,Insert
	Gui,Add,Button,x+5 greset hwndb4,Reset
	ControlSetText,Edit3,0,% win.h([10])
	if text:=scin.2161{		
		f:=scin
		AutoTrim,On
		VarSetCapacity(text,f.2161),f.2161(f.2161,&text)
		text:=Trim(strget(&text,length,utf-16))
		RegExMatch(text,"A)(.*)(,| )",fart)
		if fart1=MsgBox
		MsgBox %text%
	}
	Gui,Show,AutoSize,Msgbox Creator
	for a,b in [b1,b2,b3,b4]
	new button(b)
	Button.Redraw()
	return
	10GuiEscape:
	Gui,10:Destroy
	return
	test:
	gosub,compilemsgbox
	FileDelete,msgboxtemp.ahk
	FileAppend,%comp%,msgboxtemp.ahk
	run,msgboxtemp.ahk
	return
	copy:
	gosub,compilemsgbox
	Clipboard:=comp
	return
	insert:
	gosub,compilemsgbox
	scin.2003(scin.2008,comp)
	return
	reset:
	msgbox_creator()
	return
	compilemsgbox:
	Gui,Submit,Nohide
	for a,b in [11,12,13,14,15]{
		ControlGet,value,Checked,,Button%b%
		number:=A_Index
		if value
		break
	}
	icon:={1:0,2:16,3:32,4:48,5:64}
	for a,b in [3,4,5,6,7,8,9]{
		ControlGet,value,Checked,,Button%b%
		buttons:=A_Index-1
		if value
		break
	}
	ControlGet,value,Checked,,Button10
	help:=value?16384:0
	for a,b in [20,21,22,23]{
		ControlGet,value,Checked,,Button%b%
		modaln:=A_Index
		if value
		break
	}
	modal:={1:0,2:8192,3:262144,4:4069}
	for a,b in [24,25,26]{
		ControlGet,value,Checked,,Button%b%
		Defaultb:=A_Index
		if value
		break
	}
	default:={1:0,2:256,3:512}
	ControlGet,right,Checked,,Button27
	ControlGet,reverse,Checked,,Button28 
	right:=right?524288:0,reverse:=reverse?1048576:0
	total:=icon[number]+buttons+help+modal[modaln]+default[defaultb]+right+reverse
	comp=MsgBox,%total%,%title%,%text%,%timeout%
	return
}
t(x*){
	for a,b in x
	list.=b "`n"
	ToolTip,%list%
}
m(x*){
	for a,b in x
	list.=b "`n"
	MsgBox,% list
}
run(){
	save()
	main:=sci.main()
	SplitPath,main,name,dir
	if main=%A_ScriptFullPath%
	{
		run,%name%,%dir%
		return
		ExitApp
	}
	debug:=settings.ssn("//Debug").text
	if debug
	rundebug(main)
	else
	run,%name%,%dir%
}
;segalion http://www.autohotkey.com/community/viewtopic.php?f=2&t=16823&start=105
class cli{
	__New(sCmd, sDir="")
	{
		DllCall("CreatePipe","Ptr*",hStdInRd,"Ptr*",hStdInWr,"Uint",0,"Uint",0)
		DllCall("CreatePipe","Ptr*",hStdOutRd,"Ptr*",hStdOutWr,"Uint",0,"Uint",0)
		DllCall("SetHandleInformation","Ptr",hStdInRd,"Uint",1,"Uint",1)
		DllCall("SetHandleInformation","Ptr",hStdOutWr,"Uint",1,"Uint",1)
		l:=A_PtrSize=4?[16,68,44,56,60,64]:[24,96,60,80,88,96]
		VarSetCapacity(pi,l.1,0)
		sisize:=VarSetCapacity(si,l.2,0)
		NumPut(sisize,si,0,"UInt"),NumPut(0x100,si,l.3,"UInt"),NumPut(hStdInRd,si,l.4,"Ptr"),NumPut(hStdOutWr,si,l.5,"Ptr"),NumPut(hStdOutWr,si,l.6,"Ptr")
		DllCall("CreateProcess", "Uint", 0, "Ptr", &sCmd, "Uint", 0, "Uint", 0, "Int", True, "Uint", 0x08000000, "Uint", 0, "Ptr", sDir ? &sDir : 0, "Ptr", &si, "Ptr", &pi)
		DllCall("WriteFile","UPtr",foo,"Str",Script,"UInt",StrLen(Script) << !!A_IsUnicode,"UPtr",0,"UPtr",0)
		DllCall("CloseHandle","Ptr",NumGet(pi,0))
		DllCall("CloseHandle","Ptr",NumGet(pi,A_PtrSize))
		DllCall("CloseHandle","Ptr",hStdOutWr)
		DllCall("CloseHandle","Ptr",hStdInRd)
		this.hStdInWr:= hStdInWr, this.hStdOutRd:= hStdOutRd
	}
	close(){
		hStdInWr:=this.hStdInWr
		hStdOutRd:=this.hStdOutRd
		DllCall("CloseHandle","Ptr",hStdInWr)
		DllCall("CloseHandle","Ptr",hStdOutRd)
	}
	stdout(chars="",codepage="") {
		hStdOutRd:=this.hStdOutRd
		if (codepage="")
		codepage:=A_FileEncoding
		fout:=FileOpen(hStdOutRd, "h", codepage)
		if (IsObject(fout) and fout.AtEOF=0)
		return fout.Read()
		return ""
	}
}
rundebug(file){
	static netsh
	save(),sc:=scin
	FileEncoding,CP850
	netsh.close()
	SplitPath,file,fn,dir
	file="%file%"
	netsh:= new cli(a_ahkpath " /ErrorStdOut " file,dir)
	loop,20
	{
		sleep,20
		debug:=netsh.stdout()
		if debug
		break
	}
	if !debug
	return
	RegExMatch(debug,"Ui)(.*) \(",file),RegExMatch(debug,"U)\((.*)\)",line),RegExMatch(debug,"i)Specifically:(.*)",out)
	out:=substr(out,15),select_file(file1),sc.2024(line1-1),sc.2190(sc.2008),sc.2192(sc.2006),start:=sc.2197(strlen(out),out)
	if out1
	sc.2160(start,start+strlen(out))
	else
	sc.2160(sc.2128(line1-1),sc.2136(line1-1))
	sc.2200(sc.2008,debug)
}
var(x=""){
	static
	static list:=[]
	if !IsObject(x)
	return list[x]
	for a,b in x
	list[a]:=b
}
autoopen(file=""){
	f:=files,set:=settings
	Gui,1:Default
	Gui,TreeView,SysTreeView321
	if IsObject(file)
	TV_Delete()
	lastopen:=set.sn("//lastopen/*")
	while,last:=lastopen.item[A_Index-1]{
		if f.ssn("//*[@file='" last.text "']/@file").text
		continue
		file:=last.text,mainfilename:=last.text
		SplitPath,file,fn,maindir
		root:=TV_Add(fn,"","Icon2")
		main:=f.add("main",{main:last.text},"",1)
		f.add("file",{file:last.text,treeview:root,name:fn},"",1,"",main)
		FileRead,contents,% last.Text
		maincontents:=contents,newcontents:=""
		pos=1
		Menu,s,add,% files.sn("//main").length " " last.text,jumpfile
		Loop,Parse,contents,`n,`r`n
		{
			if InStr(a_loopfield,chr(35) "include"){
				file:=trim(a_loopfield)
				stringreplace,file,file,`,,%a_space%,All
				inc:=substr(a_loopfield,10),inc:=InStr(inc,"*i ")?SubStr(inc,4):inc
				SplitPath,inc,file,dir
				if InStr(inc,".."){
					stringreplace,inc,inc,/,\,all
					RegExReplace(inc,"\.\.\\","",count),newdir:=""
					nmd:=SubStr(maindir,1,InStr(maindir,"\",0,0,count)-1)
					Loop,Parse,inc,\
					if a_loopfield!=..
					newdir.="\" a_loopfield
					inc:=nmd newdir
				}
				SplitPath,inc,file,dir
				StringLower,ffn,file
				inc:=!dir?maindir "\" inc:inc
				FileRead,contents,%inc%
				if !FileExist(inc)
				continue
				child:=TV_Add(file,root,"Icon2")
				f.add("file",{file:inc,treeview:child,name:ffn,inc:A_LoopField},"",1,"",main)
				update({file:inc,contents:contents})
			}
			else
			newcontents.=A_LoopField "`r`n"
		}
		update({file:last.text,contents:newcontents})
	}
	menu,bar,add,&Scripts,:s
	f.Transform()
	Gui,1:Default
}
open(file=""){
	if !file
	FileSelectFile,file,,,,*.ahk
	if ErrorLevel
	return
	if !settings.ssn("//lastopen")
	autoopen([1]),settings.add("lastopen",{file:file})
	settings.add("file","","","","",settings.ssn("//lastopen")).text:=file
	autoopen()
	select_file(file)
}
select_file(file){
	getpos()
	s:=sci.lc
	settings.ssn("//lastopen").SetAttribute("file",file)
	fil:=files.ssn("//*[@file='" file "']")
	fi:=ssn(fil,"@sc").text
	Gui,1:Default
	Gui,TreeView,SysTreeView321
	TV_Modify(ssn(fil,"@treeview").text,"Select Focus Vis")
	if !fi
	{
		doc:=s.2375
		s.2358(0,doc)
		sci.set()
		s.2181(0,update(file))
		fil.SetAttribute("sc",doc)
		setcolor()
		s.2175
		s.2014
		goto sfend
	}
	if s.2376(0,fi)=0
	s.2358(0,fi)
	else
	fi:=ssn(fil,"@sc").text:="",select_file(file)
	sfend:
	if main:=files.ssn("//*[@sc='" s.2357 "'].."),mainfile:=ssn(main,"@main").text
	if !att:=positions.ssn("//*[@main='" mainfile "']")
	positions.add("File",{main:mainfile},"",1).SetAttribute("segment",file)
	else
	att.SetAttribute("segment",file)
	setpos(),fix_indent(2),main:=sci.main()?sci.main():files.ssn("//*[@sc='" doc "']../@main").text
	s:=scin.2357?scin.2357:doc
	WinSetTitle,% win.h([1]),,% "AHK Studio: " main " - " files.ssn("//*[@file='" file "']/@name").text
	s.2400
	s.2124(1)
	Return
	fe:
	if A_GuiEvent!=Normal
	return
	sel:=TV_GetSelection()
	file:=files.ssn("//*[@treeview='" sel "']/@file")
	select_file(file.text)
	return
}
update(x=""){
	static update:=[],updated:=[]
	s:=sci.lc
	if x.main
	return updated[x.main]:=1
	if x.update
	return updated
	if x.fn
	{
		if !updated[x.fn]
		TV_Modify(TV_GetSelection(),"Icon1")
		return update[x.fn]:=s.gettext(),updated[x.fn]:=1
	}
	if x.file
	return update[x.file]:=x.contents
	if update[x]
	return update[x]
	if x.clear
	return updated:=[]
}
save(){
	getpos()
	updated:=update({update:1})
	for a,b in updated{
		if com:=files.ssn("//*[@main='" a "']")
		text:=compile_main(com)
		else
		text:=update(a)
		xxx:=files.ssn("//*[@file='" a "']/@treeview").Text
		TV_Modify(xxx,"Icon2")
		SplitPath,a,file,dir
		backup:=dir "\backup\" A_Now
		if !FileExist(backup)
		FileCreateDir,%backup%
		FileMove,%a%,%backup%\%file%,1
		FileAppend,%text%,%a%
		fn.=a "`n"
	}
	settings.Transform(),settings.save(),positions.save(),update({clear:1})
}
compile_main(com){
	list:=update(ssn(com,"@main").text)
	list:=trim(list,"`r`n")
	compile:=sn(com,"*")
	while,value:=compile.item[A_Index-1]
	if v:=ssn(value,"@inc").text
	list.="`r`n" v
	return list
}
fix_indent(x=""){
	fix:=settings.ssn("//Auto_Fix_Indentation").text
	OnMessage(0x4E,"")
	sc:=sci.lc,sc.2029(0),ind:=settings.ssn("//Indent").text,
	ind:=ind?ind:5,
	out:=sc.gettext()
	indent:=0
	fix:=fix!=""?fix:0
	sc.2124(1)
	sc.2078
	loop,parse,out,`r,`r`n
	{
		cline:=A_Index-1,text:=trim(a_loopfield)
		if InStr(text,";"){
			while,pos:=InStr(text,chr(59),0,1,A_Index){ 
				in:=sc.2127(cline)
				if sc.2010(sc.2128(cline)+pos)=1
				text:=trim(substr(a_loopfield,1,pos))
			}
		} 
		if (text="*/"){
			indent-=ind
			if indent < 0
			indent:=0
			if (fix || x=1)
			;sc.2126(A_Index-1,indent+ind)
			sc.2126(A_Index-1,indent)
		}
		if (text="/*"){
			indent+=ind
			if (fix || x=1){
				sc.2126(A_Index-1,indent-ind)
				sc.2126(A_Index,indent)
			}
			sc.2222(A_Index-1,0x2000|1024+indent-ind)
		}
		else if (SubStr(text,0)="{"){
			indent+=ind
			if (fix || x=1){
				sc.2126(A_Index-1,indent-ind)
				sc.2126(A_Index,indent)
			}
			sc.2222(A_Index-1,0x2000|1024+indent-ind)
		} 
		else if (fix || x=1)
		sc.2126(A_Index-1,indent)
		if (SubStr(text,1,1)="}"){
			indent-=ind
			if indent < 0
			indent:=0
			if (fix || x=1)
			sc.2126(A_Index-1,indent)
		}
		sc.2222(A_Index,1024+indent)
		list.=A_Index " " indent "`n"
		if indent < 0
		indent:=0
	}
	if indent>0
	tooltip,Segment is open,0,0,10
	else
	ToolTip,,,,10
	if (fix=0&&x!=2)
	{
		line:=sc.2166(sc.2008),currentindent:=sc.2127(sc.2166(sc.2008)-1),linetext:=sc.textrange(sc.2128(line-1),sc.2136(line-1))
		if position:=instr(linetext,chr(59))
		linetext:=trim(substr(linetext,1,position))
		if SubStr(linetext,0)="{"
		currentindent+=ind
		line:=sc.2166(sc.2008)
		sc.2126(line,currentindent)
	}
	splashtextoff
	OnMessage(0x4E, "Notify")
	size:=settings.ssn("//Style5/@size").text?5:32
	sc.2242(0,sc.2276(size,[sc.2154 1]))
	sc.2079
}
fix_indentation(){
	s:=sci.lc
	s.2078
	fix_indent()
	s.2079
}
jump_to_segment(){
	static
	s:=sci.lc,main:=files.sn("//*[@sc='" s.2357 "']/../*/@name")
	window({num:2,title:"Jump to Segment",options:"+ToolWindow",gui:[["edit","vedit gjtsu w500"],["ListView","w500 h500 -Multi","Jump to Segment"],["Button","Default w500 gjts","Jump"]]
	,GuiSize:{Edit1:"w",SysListView321:"wh",Button1:"yw"}})
	Gui,2:Default
	while,file:=main.item[A_Index-1]
	LV_Add("",file.text)
	LV_Modify(1,"Select Focus"),hotkey({up:{jtsud:2},down:{jtsud:2}}),LV_ModifyCol(1,"AutoHDR")
	return
	jts:
	Gui,2:Default
	LV_GetText(segment,LV_GetNext()),main:=sci.main(1)
	if seg:=ssn(main,"file[@name='" segment "']/@file").Text
	select_file(seg)
	Gui,2:Destroy
	return
	jtsu:
	LV_Delete()
	while,file:=main.item[A_Index-1].text
	if InStr(file,window({get:2}).edit)
	LV_Add("",file)
	LV_Modify(1,"Select Focus")
	return
	jtsud:
	Gui,2:Default
	count:=A_ThisHotkey="up"?-1:1,pos:=LV_GetNext()+count<1?1:LV_GetNext()+count
	LV_Modify(pos,"Select Focus Vis")
	return
}
exit(){
	getpos()
	settings.add("zoom","",scin.2374)
	save()
	rebar.getlayout(lay)
	max:=win.getwinpos(x,y,w,h,win.h(1))
	if Max=Maximize
	settings.add("Gui/window1/position",{max:1})
	else
	settings.add("Gui/window1/position",{x:x,y:y,w:w,h:h,bar:lay,max:0})
	settings.Transform(),settings.save(),positions.save(),update({clear:1})
	ExitApp
}
open_folder(){
	s:=scin
	main:=sci.main()
	SplitPath,main,,dir
	run,%dir%
}
replace(){
	s:=sci.lc
	x:=s.textrange(start:=s.2266(s.2008-1,1),s.2267(s.2008-1,1))
	t:=settings.ssn("//replacements/*[@replace='" x "']").text
	if t
	s.2190(start),s.2192(start+StrLen(x)),s.2194(StrLen(t),t)
}
edit_replacements(){
	static
	Gui,7:Destroy
	Gui,7:+hwnder +Owner1
	win.h(7,er),colors()
	Gui,7:Default
	Gui,Add,ListView,w500 h500,String|Replacement
	Gui,Add,Text,Section,String
	Gui,Add,Edit,ys ver1 w300
	Gui,Add,Text,xs Section,Replacement
	Gui,Add,Edit,ver2 ys w300
	Gui,Add,Button,gera xs Default,Add Replacement
	Gui,Add,Button,gerd x+10,Remove Selected Replacement
	Gui,Show,,Edit Replacements
	erpop:
	LV_Delete()
	rep:=settings.sn("//replacements/*")
	while,v:=rep.item[A_Index-1]
	LV_Add("",ssn(v,"@replace").text,v.text)
	return
	era:
	Gui,7:Submit,Nohide
	if er1&&er2
	{
		if !main:=settings.ssn("//*[@replace='" er1 "']")
		{
			if !main:=settings.ssn("//replacements")
			main:=settings.add("//replacements")
			settings.add("replacement",{replace:er1},er2,"","",main)
		}
		else
		main.text:=er2
		loop,2
		ControlSetText,Edit%A_Index%
		ControlFocus,Edit1
		goto erpop
	}
	return
	erd:
	while,LV_GetNext(){
		LV_GetText(string,LV_GetNext())
		this:=settings.ssn("//*[@replace='" string "']")
		this.parentnode.removechild(this)
		LV_Delete(LV_GetNext())
	}
	return
	7GuiEscape:
	Gui,7:Destroy
	return
}
scintilla_code_lookup(){
	static
	IfNotExist,scintilla.xml
	{
		SplashTextOn,300,100,Downloading definitions,Please wait
		URLDownloadToFile,http://www.autohotkey.net/~maestrith/AHKStudio/scintilla.xml,scintilla.xml
		FileRead,sc,scintilla.xml
		FileDelete,scintilla.xml
		FileAppend,%sc%,scintilla.xml
		SplashTextOff
	}
	window({num:6,title:"Scintilla Code Lookup",Gui:[["Edit","gscle vedit w800"],["ListView","w800 h600 -Multi","Name|Code|Syntax"]
	,["Button","gscl Default","Add selected to script"],["Button","gscweb x+10","Goto Scintilla Documentation Website"]]
	,GuiSize:{Button1:"y",Button2:"y",SysListView321:"wh"}})
	hotkey({up:{sclhk:6},down:{sclhk:6}})
	gosub,scle
	return
	scl:
	Gui,6:Default
	LV_GetText(code,LV_GetNext(),2),s:=scin,s.2003(s.2008,[code]),s.2160(s.2008+StrLen(code),s.2008+StrLen(code))
	return
	scle:
	edit:=window({get:6}).edit
	Gui,6:Default
	GuiControl,-Redraw,SysListView321
	LV_Delete()
	StringUpper,edit,edit
	if !IsObject(temp)
	root:=scload()
	codes:=sn(root,"/*/*[contains(@name,'" edit "')]")
	sleep,0
	while,line:=codes.item[A_Index-1]
	LV_Add("",line.nodename,ssn(line,"@code").text,ssn(line,"@syntax").text)
	loop,3
	LV_ModifyCol(A_Index,"autohdr")
	LV_Modify(1,"select")
	GuiControl,+Redraw,SysListView321
	return
	scweb:
	run,http://www.scintilla.org/ScintillaDoc.html
	return
	sclhk:
	Gui,6:Default
	count:=A_ThisHotkey="up"?-1:1,pos:=LV_GetNext()+count<1?1:LV_GetNext()+count
	LV_Modify(pos,"Select Focus Vis")
	return
}
scload(){
	static
	if !IsObject(temp)
	temp:=ComObjCreate("MSXML2.DOMDocument"),temp.setProperty("SelectionLanguage","XPath"),temp.load("scintilla.xml")
	return temp
}
hotkey(key){
	for a,b in key
	for c,d in b
	{
		Hotkey,IfWinActive,% win.h([d])
		Hotkey,%a%,% c,On
	}
}
hotkeys(x=0){
	oo:=x?"On":"Off"
	set:=settings.sn("//Hotkeys/*")
	for a,b in [1]{
		Hotkey,IfWinActive,% win.h([b])
		while,key:=set.item[A_Index-1]
		if key.text
		Hotkey,% key.text,hkh,%oo%
	}
	return
	hkh:
	func:=settings.ssn("//Hotkeys/*[text()='" A_ThisHotkey "']").nodename
	%func%()
	return
}
set_hotkeys(){
	node:=settings.sn("//Hotkeys/*")
	while,item:=node.item[A_Index-1]
	t(item.nodename,item.text)
}
window(info){
	static
	static var:=[],ws:=[]
	if info.get{
		v:=[],num:=info.get
		Gui,%num%:Submit,Nohide
		for a,b in var[num]
		v[a]:=%b%
		return v
	}
	for a,b in info
	%a%:=b
	Gui,%num%:Destroy
	Gui,%num%:+Resize +Owner1
	if info.options
	Gui,% num ":" info.options
	Gui,%num%:+hwndhwnd
	win.h(num,hwnd),colors(),list:=[]
	for a,b in Gui{
		if RegExMatch(b.2,"iU)\bv(.*)\b",v)
		var[num,v1]:=v1
		if (b.2=""&&b.1="Tab"){
			Gui,%num%:Tab
			continue
		}
		Gui,%num%:Add,% b.1,% b.2 " hwndhd",% b.3
		if b.1="Button"
		list[hd]:=1
	}
	Gui,%num%:Show,Hide
	win.getwinpos(xx,yy,ww,hh,hwnd),pos:=win.pos()
	for a,b in GuiSize{
		ControlGetPos,x,y,w,h,%a%,% "ahk_id " hwnd
		Loop,Parse,b
		{
			if A_LoopField in x,w
			ws[num,a,A_LoopField]:=A_LoopField="x"?%A_LoopField%-(pos.Border*2):%A_LoopField%-ww
			if A_LoopField in y,h
			ws[num,a,A_LoopField]:=A_LoopField="y"?%A_LoopField%-hh-pos.caption-pos.border:%A_LoopField%-hh
		}
	}
	if !InStr(info.options,"-Resize")
	setguipos(ws)
	ea:=xml.easyatt(settings.ssn("//Gui/Position/Window" num))
	position:=""
	if ea.x&&ea.y&&ea.w&&ea.h
	position:="x" ea.x " y" ea.y " w" ea.w " h" ea.h
	if !info.hide
	Gui,%num%:Show,%position%,%title%
	if !IsLabel(num "guiescape")
	Hotkey({Escape:{winescape:num}})
	for a,b in List
	new Button(a),nn:=A_Index
	Button.Redraw()
	return list
}
winescape(){
	winescape:
	nw:=[]
	if (winactive()!=win.h(1)){
		for a,b in win.h()
		if (WinActive()=b&&a+0){
			Gui,%a%:Destroy
			ToolTip
		}
	}
	return
}
setguipos(a,lparam="",c="",d=""){
	static ws
	pos:=win.pos()
	if A_Gui=17
	return
	if IsObject(a){
		ws:=a
		return
	}
	for a in ws[A_Gui]{
		p=
		for b,c in ws[A_Gui,a]{
			if b in w,x
			p.=b (lparam&0xffff)+c " "
			else if b in h,y
			p.=b (lparam>>16)+c " "
		}
		GuiControl,%A_Gui%:Move,%a%,%p%
	}
}
find(){
	static s
	s:=sci.lc,main:=sci.main()
	find:=positions.ssn("//*[@main='" main "']/@find").text
	sort:=positions.ssn("//*[@main='" main "']/@sort").text
	window({num:12,title:"Find",options:"+ToolWindow",gui:[["Edit","w500 vfind gfindedit",find],["TreeView","w500 h500 gfindtv AltSubmit"]
	,["Checkbox","vsort " sort,"Sort by segment"],["Button","default gfind","Search"]]
	,GuiSize:{Button1:"y",Button2:"y",SysTreeView321:"wh",Edit1:"w"}})
	return
	find:
	info:=window({get:12}),find:=info.find,main:=sci.main(),positions.add("File",{main:main,find:find,sort:sort:=info.sort?"Checked":""},"","",{main:main})
	controlgetfocus,out,% win.h([12])
	if out!=SysTreeView321
	return check()
	TV_GetText(top,TV_GetSelection())
	exist:=FileExist(top),exp:=TV_Get(TV_GetSelection(),"E")
	if (exist&&exp=0){
		TV_Modify(TV_GetSelection(),"Expand")
		goto findtv
	}
	if (exist&&exp!=0){
		TV_Modify(TV_GetSelection(),"-Expand")
		goto findtv
	}
	child:=tv_getchild(tv_getselection())
	tv_gettext(position,child)
	tv_gettext(file,tv_getnext(child))
	child:=tv_getchild(tv_getselection())
	tv_gettext(position,child)
	tv_gettext(file,tv_getnext(child))
	if !File
	return
	select_file(file),Button.Redraw(),s.2025(position),s.2160(position,position+strlen(find))
	ControlFocus,SysTreeView321,% win.h([12])
	return
	findtv:
	ControlGetFocus,Focus,% win.h([12])
	if !InStr(Focus,"SysTreeView321"){
		ControlSetText,Button2,Search,% win.h([12])
		return
	}
	TV_GetText(top,TV_GetSelection())
	if !Top
	return
	If FileExist(top)
	ControlSetText,Button2,Expand,% win.h([12])
	else
	ControlSetText,Button2,Select,% win.h([12])
	if TV_Get(TV_GetSelection(),"E")
	ControlSetText,Button2,Contract,% win.h([12])
	return
	findedit:
	ControlSetText,Button2,Search,% win.h([12])
	return
}
check(){
	Gui,12:Default
	root:=sn(files.ssn("//*[@sc='" sci.lc.2357 "'].."),"*/@file")
	TV_Delete()
	info:=window({get:12}),find:=info.find,sort:=info.sort
	if !find
	return
	find=\Q%find%\E
	GuiControl,-Redraw,SysTreeView321
	while,file:=root.item[a_index-1].nodevalue,out:=update(file){
		found:=1
		while found:=RegExMatch(out,"iO)(.*)(" find ")(.*)",fo,found){
			text:=Trim(fo.value())
			r:=sort&&A_Index=1?TV_Add(file):r
			parent:=TV_Add(text,r)
			TV_Add(fo.pos(2)-1,parent)
			TV_Add(file,parent)
			found+=fo.len()
		}
	}
	if TV_GetCount()
	controlfocus,SysTreeView321
	GuiControl,+Redraw,SysTreeView321
}
getpos(){
	s:=sci.lc
	find:=[]
	main:=files.ssn("//*[@sc='" s.2357 "']/@file")
	if !Main.text
	return
	fold:=0
	while,s.2618(fold)>=0,fold:=s.2618(fold)
	list.=fold ",",fold++
	fold:=trim(list,",")
	parent:=files.ssn("//*[@sc='" s.2357 "']../@main").text,mainfile:=main.text,p:=regexreplace(parent,"[^a-zA-Z]")
	splitpath,mainfile,ff
	m:=regexreplace(ff,"[^a-zA-Z]"),posdata:={fold:fold,min:s.2009,max:s.2008,scroll:s.2152}
	under:=positions.ssn("//*[@main='" parent "']")
	if !find:=ssn(under,m)
	positions.add(m,posdata,"","","",under)
	else
	for a,b in posdata
	find.SetAttribute(a,b)
}
setpos(){
	s:=sci.lc
	file:=files.ssn("//*[@sc='" s.2357 "']/@file").text,parent:=files.ssn("//*[@sc='" s.2357 "']../@main").Text
	SplitPath,file,ff
	f:=regexreplace(ff,"[^a-zA-Z]"),pos:=positions.ssn("//*[@main='" parent "']")
	if (pos.xml){
		pos:=sn(pos,f "/@*")
		while,x:=pos.item[A_Index-1]{
			item:=x.nodename
			%item%:=x.text
		}
		if !min
		return
		s.2024(s.2166(min)),s.2613(scroll),s.2160(max,min)
		Loop,Parse,fold,`,
		s.2231(A_LoopField)
	}
}
find_in_segment(){
	static
	find:=positions.ssn("//*[@main='" sci.main() "']/@fis").text
	window({num:5,title:"Find In Segment",Gui:[["Text","Section","Enter text to find"],["Edit","x+5 w200",find]
	,["Radio","xs vnext","Previous"],["Radio","Checked","Next"],["Button","gfis Default","Search"]]
	,GuiSize:{Edit1:"w"}})
	Hotkey({up:{fissel:5},down:{fissel:5}})
	return
	fissel:
	sel:=A_ThisHotkey="down"?"Next":"Previous"
	GuiControl,5:,%sel%,1
	return
	fis:
	controlget,previous,checked,,Previous
	controlgettext,out,Edit1,% win.h([5])
	s:=scin,main:=sci.main(),positions.add("File",{main:main,fis:out},"","",{main:main}),s.2190(s.2008-previous)
	if previous
	s.2192(0)
	else
	s.2192(s.2006)
	start:=s.2197(strlen(out),[out])
	if start=-1
	return be:=previous=1?"beginning":"end",m("Reached the " be " of the selection.")
	S.2160(start,start+strlen(out))
	return
}
replace_text(){
	window({num:16,title:"Replace Text",Gui:[["Text","Section","Text to find:"],["Edit","vfind x+10 grtd"],["Text","xs Section","Text to replace:"]
	,["Edit","x+10 vreplace"]
	,["Radio","vall xs grtd","Search in all segments"],["Radio","vcurrent Checked grtd","Search in current segment"],["Radio","vselected grtd","Search in selected text"]
	,["Button","grt Default","Find"],["Button","grtn Disabled x+10","Find Next"],["Button","grtr Disabled x+10","Replace"]]
	,GuiSize:{Edit1:"w",Edit2:"w"}})
	return
	rt:
	s:=scin,pos:=end:="",var:=window({get:16}),find:=var.find,replace:=var.replace,info:=win.posinfo()
	if !find
	return
	list:=[],rep:=[]
	if var.all
	search:=files.sn("//*[@sc='" s.2357 "']../*")
	if var.selected
	search:=files.sn("//*[@sc='" s.2357 "']"),pos:=info.start,end:=info.end,rep["start"]:=pos,rep["end"]:=end
	if var.current
	search:=files.sn("//*[@sc='" s.2357 "']")
	while,file:=search.item[A_Index-1].SelectSingleNode("@file").text{
		code:=update(file),pos:=pos?pos:1,filenum:=A_Index
		if InStr(code,find)
		val:=fun.value(0),list[filenum]:={num:filenum,name:file}
	}
	foundin:=[]
	for a,b in List
	foundin.Insert(b)
	if !foundin.1
	return m("Unable to find the specified text.")
	rep["list"]:=foundin
	rep["find"]:=find
	rep["replace"]:=var.replace
	loopit(rep)
	return
	for a,b in replace
	s.2160(a,b),m("here")
	return
}
loopit(replace){
	static
	rep:=replace,replist:=replace["list"]
	c:=0,listnum:=1,list:=replist[listnum].num
	foundpos:=rep.start?rep.start:0
	for a,b in [5,6]
	GuiControl,16:Enable,Button%b%
	ControlFocus,Button4,% win.h([16])
	Send,{Down}
	rtr:
	rtn:
	s:=scin
	if A_ThisLabel=rtr
	s.2170(0,rep.replace)
	if replist[listnum].num
	select_file(replist[listnum].name)
	else
	{
		rtd:
		for a,b in [5,6]
		GuiControl,16:Disable,Button%b%
		if A_ThisLabel=rtd
		return
		return m("No more occurrences")
	}
	searchend:=rep.end?rep.end:s.2006
	s.2190(foundpos),s.2192(searchend)
	start:=s.2197(strlen(rep.find),[rep.find])
	s.2160(start,start+StrLen(rep.find))
	foundpos:=start+1
	if (foundpos=0){
		listnum++,list:=replist[listnum].num,foundpos:=0
		goto rtn
	}
	return
}
remove_current_segment(){
	s:=scin
	root:=files.ssn("//*[@sc='" s.2357 "']"),mm:=ssn(root,"../@main").text,ff:=ssn(root,"@name").text,fn:=ssn(root,"@file").text
	if (mm=fn)
	return m("The main file can not be removed.")
	MsgBox,4,Are you sure?,Remove %current% from the current project?
	IfMsgBox,No
	return
	MsgBox,4,Delete the file from your computer?,Also delete the file?
	IfMsgBox,Yes
	FileDelete,%ff%
	sc:=ssn(root,"@sc").text,tv:=ssn(root,"@treeview").text
	s.2377(0,sc)
	Gui,1:Default
	TV_Delete(tv)
	select_file(mm)
	root.parentnode.removechild(root)
	update({main:mm})
}
new_segment(new=""){
	s:=scin
	{
		root:=files.ssn("//*[@sc='" s.2357 "']"),main:=ssn(root,".."),mm:=ssn(root,"../@main").text,view:=files.ssn("//*[@file='" mm "']/@treeview").text
		SplitPath,mm,,dir
	}
	if !new
	FileSelectFile,new,s,%dir%\,Create a new Segment,*.ahk
	if ErrorLevel
	return
	if ssn(main,"*[@file='" new "']")
	return select_file(new)
	SplitPath,new,file,newdir
	include:=newdir=dir?chr(35) "include " file:chr(35) "include " new
	Gui,1:Default
	Gui,TreeView,SysTreeView321
	tv:=TV_Add(file,view)
	doc:=s.2375
	files.add("file",{file:new,inc:include,treeview:tv,sc:doc,name:file},"","","",main)
	FileAppend, ,%new%
	select_file(new),sci.set()
	update({main:mm})
}
export(){
	FileSelectFile,filename,S 16,,Export file as?,AHK (*.ahk)
	if ErrorLevel
	return
	filename:=InStr(filename,".ahk")?filename:filename ".ahk"
	IfExist,%filename%
	FileDelete,%filename%
	FileAppend,% publish(1),%filename%
}
character_count(){
	s:=scin
	if s.2161>1
	m(s.2161-1)
	else
	m(s.2183)
}
cut(){
	scin.2177
}
copy(){
	scin.2178
}
pastectrl_v(){
	scin.2179
}
Full_Backup(){
	save(),s:=scin
	SplashTextOn,300,100,Backing up...,Please wait, This may take some time if it has been a while since your last full backup.
	main:=files.ssn("//*[@sc='" s.2357 "']../@main").text
	SplitPath,main,,dir
	backup:=dir "\backup\Full Backup" A_Now
	FileCreateDir,%backup%
	loop,%dir%\*.*
	{
		if InStr(a_loopfilename,".exe") || InStr(A_LoopFileName,".dll")
		continue
		filecopy,%A_LoopFileFullPath%,%backup%\%A_LoopFileName%
	}
	loop,%dir%\backup\*.*,2
	if !InStr(A_LoopFileFullPath,"Full Backup")
	fileremovedir,%a_loopfilefullpath%,1
	SplashTextOff
}
publish(x=""){
	s:=scin
	com:=files.ssn("//*[@sc='" s.2357 "'].."),main:=ssn(com,"@main").text
	list:=update(ssn(com,"@main").text)
	list:=trim(list,"`r`n")
	compile:=sn(com,"*")
	while,value:=compile.item[A_Index-1]
	if v:=ssn(value,"@file").text{
		if (v=main)
		continue
		v:=trim(update(v),"`r`n")
		list.="`r`n" v
	}
	filename:=files.ssn("//*[@sc='" s.2357 "']../@main").text
	version:=xml.xk("version")
	ver:=xml.easyatt(version.ssn("//*[@file='" filename "']"))
	version:=ver.version
	StringReplace,list,list,% chr(59) "auto_version",Version=%version%
	if x
	return list
	clipboard:=list
	MsgBox,,,Project coppied to your clipboard,.6
}
brace(){
	brace:
	pi:=win.posinfo(),s:=sci.lc,s.2078
	if settings.ssn("//Simple_Brace").Text{
		if (pi.ind=pi.lineend&&A_ThisHotkey="{"){
			s.2003(s.2008,"{`n`n}")
			currentindent:=s.2127(s.2166(s.2008))
			line:=s.2166(s.2008)+1
			s.2126(line,currentindent+5)
			s.2126(line+1,currentindent)
			send,{down}^{right}
			fix_indent()
			s.2079
			return
		}
		list:={"[":"]","{":"}","(":")"}
		s.2003(pi.start,A_ThisHotkey),s.2003(pi.end+1,list[A_ThisHotkey]),s.2160(s.2008+1,s.2008+1)
	}
	else
	cur:=s.2008,s.2003(cur,A_ThisHotkey),s.2160(cur+1,cur+1)
	s.2079
	return
}
moveline(){
	moveline:
	s:=scin,pos:=win.posinfo()
	static updn:={"+^up":2620,"+^down":2621}
	s[updn[A_ThisHotkey]]
	return
}
toggle_comment_line(){
	pi:=win.posinfo(),s:=scin,s.2078,sl:=s.2166(pi.start),el:=s.2166(pi.end),end:=pi.end,single:=sl=el?1:0
	while,sl<=el{
		letter:=s.textrange(min:=s.2128(sl),min+1)
		if (min>end&&!single)
		break
		if (letter=";")
		s.2190(min),s.2192(min+1),s.2194(0,""),end--
		else
		s.2190(min),s.2192(min),s.2194(1,";"),end++
		sl++
	}
	s.2079
}
hotkeymenu(){
	static menu:=[]
	Menu,hot,Add,Settings,settings
	for a,b in constants("hotkeys"){
		if a=headderval
		continue
		if InStr(a,"paste")
		continue
		hotkey:=""
		if a=headerval
		continue
		hotkey:=thiskey:=settings.ssn("//Hotkeys/" clean(a)).text
		for c,d in [{"+":"Shift+"},{"!":"Alt+"},{"^":"Ctrl+"}]
		for e,f in d
		hotkey:=InStr(Hotkey,e)?RegExReplace(Hotkey,"\" e,f):hotkey
		if menu[a]
		Menu,hot,Delete,% menu[a]
		Menu,Hot,Add,%a%`t%hotkey%,hotkeymenu
		if !IsFunc(clean(a,1))
		Menu,hot,Disable,%a%`t%hotkey%
		menu[a]:=a "`t" hotkey
	}
	Menu,bar,Add,&Hotkey Actions,:Hot
	return
	hotkeymenu:
	key:=SubStr(A_ThisMenuItem,1,InStr(A_ThisMenuItem,"`t")-1)
	key:=clean(key)
	%key%()
	return
}
show_scintilla_code_in_line(){
	s:=scin
	line:=s.2166(sc.2008)
	if s.2546(line){
		sc.2547
		return
	}
	IfNotExist,scintilla.xml
	{
		SplashTextOn,300,100,Downloading definitions,Please wait
		URLDownloadToFile,http://www.autohotkey.net/~maestrith/scintilla.xml,scintilla.xml
		SplashTextOff
	}
	root:=scload(),text:=s.textrange(s.2128(s.2166(s.2008)),s.2136(s.2166(s.2008)))
	found:=RegExReplace(text,"([^0-9])","`n")
	loop,Parse,found,`n
	if A_LoopField
	{
		if StrLen(A_LoopField)<4
		continue
		Number.=A_LoopField "="
		node:=sn(root,"//scintilla/*[@code='" A_LoopField "']")
		while,nn:=node.item[A_Index-1].nodename
		number.= nn " "
		Number.="`n"
	} 
	if !Trim(number,"`n")
	return
	m(trim(number,"`n"))
	return
}
Theme(){
	static
	Gui,9:Destroy
	Gui,9:+hwndec
	win.h(9,ec)
	Hotkey({RButton:{fontstyle:9},Escape:{fontclose:9}})
	s:=new sci(ec,"color",0,0,800,700)
	out=/*`nMulti-Line`ncomments`n*/`nSelect the text to change the colors`nThis is a sample of normal text`n`"incomplete quote`n"complete quote"`n`;comment`n0123456789`n()[]^&*()+~`{`}``b``a``c``k``t``i``c``k`n
	loop,10
	out.=keywords(a_index) "`n"
	out.="Goto 'Edit/Edit highlight text' to add/edit your own personal highlight list.`n`nRight click to change the style of each font.`n`nLeft click to change the color of a style.`n`nIf you hold down the control key when you click it will change the background color.`n`n<----To change the background of the numbers bar hold Control+Click"
	s.2181(0,out),s.2246(0,1),s.2069(0xFFFFFF)
	Gui,9:Show,w800 h720,Theme
	s.2160(0,0),sci.set(),s.2246(0,1),setcolor()
	loop,34
	s.2409(A_Index-1,1)
	s.2029(0)
	Menu,Default,Add,Restore fonts to default,fontlabel
	Menu,Default,Add,Default Background Color,dbc
	Menu,Default,Add,Clear Background Colors,dcbc
	menu:={"Word Wrap Marker Color":"wwmc","Caret Color":2069,"Show Selected Duplicates":"ssd","Multiple Selection Color":"msc","Main Selection Color":"ssb","Match Brace Highlight":34}
	for a,b in Menu
	Menu,Default,Add,%a%,fmcc
	Menu,ec,Add,&Color Options,:Default
	Menu,save,Add,Import From File,fontb
	Menu,save,Add,Export to File,fontb
	Menu,save,Add,Save Current,fontb
	Menu,save,Add,Remove Themes,removepre
	Menu,save,Add,Download Themes,dltheme
	Menu,ec,Add,Theme Options,:save
	sv:=settings.sn("//Preset/*")
	while,q:=sv.item[A_Index-1]{
		Menu,list,Add,% q.nodename,applystyle
		l:=A_Index
	}
	Menu,ec,Add,Theme List,:list
	Menu,ec,Add,Word Wrap,tww
	Menu,ec,Add,Buttons,tbtn
	;Menu,ec,Add,Buttons,:btn
	gui,9:menu,ec
	s.2130(1),s.2460(3),s.2462(1)
	list:=""
	return
	dltheme:
	Run,http://code.google.com/p/ahk-studio/downloads/list
	return
	tww:
	wrap:=sci.hw.color.2269
	sci.hw.color.2268(out:=wrap?0:1)
	return
	applystyle:
	if new:=settings.ssn("//Preset/" A_ThisMenuItem "/Fonts"){
		if fonts:=settings.ssn("//Gui/Fonts")
		fonts.parentnode.removechild(fonts)
		gui:=settings.ssn("//Gui")
		dup:=new.clonenode(1)
		gui.appendchild(dup),
		keywords(98)
		setcolor()
	}
	return
	fontb:
	if InStr(A_ThisMenuItem,"Export"){
		temp:=""
		temp:=ComObjCreate("MSXML2.DOMDocument"),temp.setProperty("SelectionLanguage","XPath")
		FileSelectFile,out,S16,,Select a File for Export,*.xml
		if ErrorLevel
		return
		out:=InStr(out,".xml")?out:out ".xml"
		FileDelete,%out%
		Root:=temp.CreateElement("AHK_Studio"),temp.appendchild(root)
		cur:=settings.ssn("//Gui/Fonts")
		cc:=cur.clonenode(1)
		root.appendchild(cc) ;,cc.appendchild(key)
		temp.transformNodeToObject(xml.style(),temp)
		temp.save(out),temp:=""
	}
	if InStr(A_ThisMenuItem,"Import"){
		temp:=ComObjCreate("MSXML2.DOMDocument"),temp.setProperty("SelectionLanguage","XPath")
		FileSelectFile,out,,,Select a preset to load,*.xml
		if ErrorLevel
		return
		temp.load(out)
		if !pre:=ssn(temp,"//AHK_Studio")
		return m("Sorry but this is not a valid preset")
		SplitPath,out,,,,name
		name:=clean(name)
		name:=regexreplace(regexreplace(name," ","_"),"i)(?:[^a-z_])","")
		if old:=settings.ssn("//Preset/" name)
		old.parentnode.removechild(old)
		new:=settings.Add("Preset/" name)
		t:=temp.SelectSingleNode("//Fonts")
		new.appendchild(t)
		temp:=""
		settings.Transform()
		theme(),temp:=""
	}
	if InStr(A_ThisMenuItem,"Save"){
		InputBox,name,Input a name for your new style,No numbers please
		if !name
		return
		name:=regexreplace(regexreplace(name," ","_"),"i)(?:[^a-z_])","")
		cur:=settings.ssn("//Gui/Fonts")
		if !main:=settings.ssn("//Preset")
		main:=settings.add("Preset")
		if next:=settings.ssn("//Preset/" name)
		next.parentnode.removechild(next)
		next:=settings.add(name,"","","","",main)
		dup:=cur.clonenode(1)
		next.appendchild(dup)
		theme()
	}
	return
	fmcc:
	color:=settings.ssn("//Style" menu[A_ThisMenuItem] "/@Color").text
	color:=dlg_color(color)
	settings.add("Gui/Fonts/Style" menu[A_ThisMenuItem],{Color:color})
	setcolor()
	return
	dcbc:
	rem:=settings.sn("//Fonts/*[@Background]")
	while,node:=rem.item[A_Index-1]
	if (node.nodename!="Style33")
	ssn(node,"@Background").text:=""
	setcolor()
	return
	fontstyle:
	MouseGetPos,xx,yy,,con
	ControlGetPos,x,y,w,h,Scintilla1,% win.h([9])
	x:=abs(xx-x),y:=abs(yy-y)
	if style:=s.2010(s.2022(x,y))
	change_font(style),setcolor()
	return
	removepre:
	list:=settings.sn("//Preset/*")
	window({num:15,title:"Delete Preset",Gui:[["ListView","w300 h500 Multi","Preset"],["Button","gpsrem","Remove Selected"]]})
	Gui,15:Default
	while,p:=list.item[A_Index-1]
	lv_add("",p.nodename)
	return
	psrem:
	Gui,15:Default
	while,LV_GetNext(){
		LV_GetText(string,LV_GetNext())
		this:=settings.ssn("//Preset/" string)
		this.parentnode.removechild(this)
		LV_Delete(LV_GetNext())
	}
	return
	15GuiClose:
	15GuiEscape:
	settings.Transform()
	settings.save()
	theme()
	Gui,15:Destroy
	return
	fontclose:
	9GuiClose:
	9GuiEscape:
	Gui,9:Destroy
	Menu,list,DeleteAll
	sci.hw.color:=""
	settings.Transform()
	settings.save()
	return
	fontlabel:
	if InStr(A_ThisMenuItem,"restore")
	MsgBox,4,Reset fonts to default,Are you sure?
	IfMsgBox,Yes
	fonts:=settings.ssn("//Fonts"),fonts.parentnode.removechild(fonts),defaultfonts(),setcolor()
	return
	dbc:
	color:=settings.ssn("//Style32/@Background").text
	color:=dlg_color(color)
	settings.add("Gui/Fonts/Style32",{Background:color})
	setcolor()
	return
	tbtn:
	theme_button()
	return
}
change_font(win){
	list:=["Font","Size","Color","Background","Bold","Italic","Underline"],num:=[win,5,32]
	for a,b in list
	for c,d in num{
		%b%:=settings.ssn("//Style" d "/@" b).Text
		if %b% || %b%=0
		break
	}
	if !dlg_font(font,style:={size:size,bold:bold,underline:underline,italic:italic},color)
	return
	settings.add("Gui/Fonts/Style" win,{Color:color,Size:style.size,Font:font,Bold:style.bold,Italic:style.italic,Underline:style.underline})
	setcolor(),colors()
}
Dlg_Font(ByRef Name,ByRef Style,ByRef Color,Effects=true,hGui=0){
	MouseGetPos,,,hgui
	strput(strget(&name),&name,"CP0")
	LogPixels:=DllCall("GetDeviceCaps","uint",DllCall("GetDC","uint",hGui),"uint",90)
	VarSetCapacity(LOGFONT,60,0)
	Effects:=0x041+(Effects ? 0x100 : 0)
	DllCall("RtlMoveMemory","uint",&LOGFONT+28,"Uint",&Name,"Uint",32)
	for a,b in {bold:{v:700,a:16},italic:{v:1,a:20},underline:{v:1,a:21}}
	if style[a]
	NumPut(b.v,logfont,b.a)
	if style.size
	{
		NumPut(-DllCall("MulDiv","int",style.size,"int",LogPixels,"int",72),LOGFONT,0,"Int")
	}
	else  NumPut(16,LOGFONT,0)
	VarSetCapacity(CHOOSEFONT,60,0),NumPut(60,CHOOSEFONT,0),NumPut(hGui,CHOOSEFONT,4),NumPut(&LOGFONT,CHOOSEFONT,12),NumPut(Effects,CHOOSEFONT,20),NumPut(color,CHOOSEFONT,24)
	r:=DllCall("comdlg32\ChooseFontA", "uint",&CHOOSEFONT)
	if !r
	return false
	VarSetCapacity(Name,32)
	DllCall("RtlMoveMemory","str",Name,"Uint",&LOGFONT + 28,"Uint",32)
	Style:="s" NumGet(CHOOSEFONT,16) // 10
	old:=A_FormatInteger
	SetFormat,integer,hex
	Color:=NumGet(CHOOSEFONT,24)
	SetFormat,integer,%old%
	Style=
	VarSetCapacity(s,3)
	DllCall("RtlMoveMemory","str",s,"Uint",&LOGFONT + 20,"Uint",3)
	bold:=NumGet(LOGFONT,16)>=700?1:0
	italic:=NumGet(LOGFONT,20,"UChar")?1:0
	underline:=NumGet(LOGFONT,21,"UChar")?1:0
	s:=NumGet(LOGFONT,0,"Int")
	style:={size:Abs(DllCall("MulDiv","int",abs(s),"int",72,"int",LogPixels)),underline:underline,italic:italic,bold:bold,name:strget(&name,cp0),color:color}
	name:=strget(&name,cp0) 
	return 1
}
Dlg_Color(Color, setcolor=""){
	VarSetCapacity(CHOOSECOLOR,0x24,0),VarSetCapacity(CUSTOM,64,0)
	,NumPut(0x24,CHOOSECOLOR,0),NumPut(WinActive(),CHOOSECOLOR,4)
	,NumPut(color,CHOOSECOLOR,12),NumPut(&CUSTOM,CHOOSECOLOR,16)
	,NumPut(0x00000103,CHOOSECOLOR,20)
	nRC:=DllCall("comdlg32\ChooseColorA", str,CHOOSECOLOR)
	setformat,integer,H
	clr := NumGet(CHOOSECOLOR,12)
	setformat,integer,D
	return %clr%
}
close(){
	close:=files.sn("//*[@sc='" scin.2357 "']../*")
	save()
	list:=files.sn("//*/main"),remove:=files.ssn("//*[@sc='" scin.2357 "']../@main").text
	while,file:=list.item[A_Index-1].selectsinglenode("@main")
	Menu,s,Delete,% A_Index " " file.text
	while,c:=close.item[A_Index-1]{
		att:=xml.easyatt(c)
		if att.sc
		scin.2377(0,att.sc)
		if att.TreeView
		TV_Delete(att.treeview)
	}
	main:=files.ssn("//*[@sc='" scin.2357 "'].."),main.parentnode.removechild(main),list:=files.sn("//*/main")
	while,file:=list.item[A_Index-1].selectsinglenode("@main")
	Menu,s,Add,% A_Index " " file.text,jumpfile
	q:=files.ssn("//@main").text
	main:=positions.ssn("//*[@main='" q "']/@segment").Text
	select_file(main)
	rem:=settings.ssn("//lastopen/file[text()='" remove "']")
	rem.parentnode.removechild(rem)
}
insert_function(){
	s:=scin
	InputBox,name,Function name,Input the name of the function
	if (ErrorLevel || name="")
	return
	InputBox,options,Function Options,Input the options for this function (eg. function(*this information) )
	if ErrorLevel
	return
	s.2003(s.2008,clean(name) "(" options "){`r`n`r`n}")
	fix_indent()
	sleep,100
	send,{down}^{right}
	;WinGet,style,style,% hwnd("h3")
	;if (style&0x10000000)
	;coderefresh()
}
/*
	working on other things atm.  I will work on it.
	create_segment_from_selection(){
		
	}
*/
import(){
	{
		MsgBox,This process does not always work on every script.`nPlease open it normally and use Create Segment from Selection if it does not.
		FileSelectFile,file,,,Select a file to import,*.ahk
		if ErrorLevel
		return
		SplitPath,file,,,,noext
		name:=noext
		IfExist,project\%noext%
		msgbox,3,Project Already Exists,Delete?`nYes: Delete and create a new project`nNo: Rename project`nCancel: Abort
		IfMsgBox,Yes
		FileRemoveDir,project\%noext%,1
		IfMsgBox,No
		FileMoveDir,project\%noext%,project\%noext%-%a_now%,1
		IfMsgBox,Cancel
		return
	}
	fileread,script,%file%
	loop,parse,script,`n,`r
	{
		if (RegExMatch(A_LoopField,"(.*\(.*\).*{)",fun) && substr(a_loopfield,0)="{")
		start=1
		if !start
		everything.=a_loopfield "`n"
		if start
		{
			stringsplit,out,a_loopfield,;
			out:=trim(out1)
			if SubStr(out,0) = "{"
			indent++
			if out = `}
			indent--
			program.=a_loopfield "`n"
			if indent=0
			{
				prognum++
				final%prognum%:=program
				program=
				start=
			}
		}
	}
	dir=%A_ScriptDir%\project\%name%
	fileremovedir,%dir%,1
	filecreatedir,%dir%
	loop,%prognum%
	fileappend,% trim(final%a_index%,"`r`n"),% dir "\" substr(final%a_index%,1,instr(final%a_index%,"(")-1)
	loop,%dir%\*.
	list.=a_loopfilename ","
	fileappend,%everything%,%dir%\%name%
	include:=chr(35) "include"
	fileappend,%include% %name%`n,%dir%\%name%.ahk
	loop,parse,list,`,
	if a_loopfield
	fileappend,%include% %a_loopfield%`n,%dir%\%name%.ahk
	open(dir "\" name ".ahk")
}
drag_drop(){
	GuiDropFiles:
	if A_EventInfo>1
	return m("One file at a time please")
	FileRead,file,%A_GuiEvent%
	SplitPath,A_GuiEvent,name
	MsgBox,3,Open file?,Include in the current project?`nNo will open it in a new project.
	IfMsgBox No
	return open(A_GuiEvent)
	IfMsgBox Cancel
	return
	s:=scin
	main:=files.ssn("//*[@sc='" s.2357 "']/..")
	m(main.xml)
	;SplitPath,main,,dir
	;FileCopy,%A_GuiEvent%,%dir%\%name%
	;if files:=sn(main,"//*[@main='" A_GuiEvent "']|//*[@file='" A_GuiEvent "']").length>1
	;return m("File already exists in the current project.  Rename the file and try again."),m(files.length)
	;new_segment(name)
	;var({wd:file})
	;settimer,dddelay,1
	return
}
Version(x=""){
	Version=0.001.79
	if x
	return version
	SplashTextOn,240,50,Downloading latest version information,Please wait
	URLDownloadToFile,http://www.autohotkey.net/~maestrith/AHKStudio/AHK Studio.text,version.ver
	SplashTextOff
	fileread,ver,version.ver
	Gui,33:Destroy
	Gui,33:+hwndhwnd
	win.h(33,hwnd),colors()
	Gui,33:Add,Edit,w500 h500,%ver%
	Gui,33:Add,Button,gvdu,Download Latest Version
	Gui,33:Show,,% "Current Version:" Version(1)
	return
	33GuiEscape:
	33GuiClose:
	Gui,33:Destroy
	return
	vdu:
	auto_update()
	return
}
auto_update(){
	save()
	splitpath,a_scriptname,,,,filename
	vn:=version(1),ext:=if A_IsCompiled?".exe":".ahk"
	filemove,%a_scriptname%,backup_%vn%_%a_scriptname%,1
	SplashTextOn,500,200,Please Wait,Downloading the new version.  This could take a minute
	urldownloadtofile,http://www.autohotkey.net/~maestrith/AHKStudio/AHK Studio%ext%,%a_scriptname%
	reload
}
upload(){
	getpos(),s:=scin
	all:=xml.easyatt(settings.ssn("//Ftp"))
	if !(all.username&&all.password&&all.server)
	return m("Your ftp server is not setup properly."),settings()
	filename:=files.ssn("//*[@sc='" s.2357 "']../@main").text
	version:=xml.xk("version")
	ver:=xml.easyatt(version.ssn("//*[@file='" filename "']")),vn:=ver.version?ver.version:1,checked:=ver.compile?"Checked":""
	window({num:13,title:"Upload",gui:[["Text","","Version:"],["Edit","w400 vversion",vn]
	,["Text","","Version information:"],["Edit","w400 h500 vinf"],["Text","","Upload Directory:"]
	,["Edit","w400 vdirectory",ver.directory],["Button","gupload Default","Upload"]
	,["Checkbox","vcompile xm " checked,"Compile and send exe"]]
	,GuiSize:{Edit1:"w",Edit2:"wh",Static3:"y",Edit3:"yw",Button1:"y",Button2:"y"}})
	vers:=ver.1
	newline=`r`n
	if !InStr(vers,vn)
	vers:=vn newline newline vers
	StringReplace,vers,vers,`n,`r`n,all
	ControlSetText,Edit2,% vers,% win.h([13])
	ControlFocus,Edit2,% win.h([13])
	Send,{Down}
	return
	upload:
	save(),x:=window({get:13})
	gosub 13GuiClose
	filedelete,temp.upload
	filename:=files.ssn("//*[@sc='" scin.2357 "']../@main").text,vv:=xml.xk("version")
	FileAppend,% publish(1),temp.upload
	vv:=xml.xk("version")
	vv.add("Script",{file:filename,version:ver(x.version),directory:x.directory,compile:x.compile},x.inf,1,{file:filename})
	SplitPath,A_AhkPath,,dir
	Loop,%dir%\Ahk2Exe.exe,1,1
	file:=A_LoopFileFullPath
	splitpath,filename,,dir,,name
	if x.compile{
		SplashTextOn,200,100,Compiling,Please wait.
		RunWait,%file% /in temp.upload /out "%dir%\%name%.exe"
		IfExist,upx.exe
		RunWait,upx.exe "%dir%\%name%.exe"
		SplashTextOff
	}
	vv.add("Script",{file:filename,directory:x.directory,compile:x.compile},x.inf,1,{file:filename})
	FileDelete,% dir "\" name ".text"
	FileAppend,% x.inf,% dir "\" name ".text"
	if x.compile
	send(x.directory,{"temp.upload":filename},dir "\" name ".exe",dir "\" name ".text")
	else
	send(x.directory,{"temp.upload":filename},dir "\" name ".text")
	Gui,13:Destroy
	return
	13GuiEscape:
	13GuiClose:
	filename:=files.ssn("//*[@sc='" scin.2357 "']../@main").text,vv:=xml.xk("version")
	x:=window({get:13})
	vv.add("Script",{file:filename,version:x.version,directory:x.directory,compile:x.compile},x.inf,1,{file:filename})
	vv.transform(),vv.save()
	Gui,13:Destroy
	return
}
send(dir,filename*){
	ftp(dir,filename)
}
ver(x){
	RegExMatch(x,"(.*)\.(.*)",f)
	if f2
	return f1 "." f2+1
	return x "." 1
}
new(){
	if !FileExist("Projects")
	FileCreateDir,Projects
	FileSelectFile,file,S,%A_ScriptDir%\Projects,,*.ahk
	if ErrorLevel
	return
	if FileExist(file)
	return m("Please choose another file.")
	file:=InStr(file,".ahk")?file:file ".ahk"
	FileAppend,,%file%
	open(file)
}
AHK_Pastebin_Code(){
	user:=settings.ssn("//Pastebin/@user").text,public:=settings.ssn("//Pastebin/@public").text
	user:=user?user:A_UserName
	check:=public?"Checked":""
	window({num:34,title:"AHK pastebin code",Gui:[["Text","Section","IRC Name:"],["Edit","x+10 w300 vircname",user]
	,["Checkbox","vpublic x+10 " Check,"Post public"]
	,["Text","Section xm","Program Description:"],["Edit","x+10 w300 vdesc","Posted using AHK Studio"]
	,["Button","gptahk xm Default","Post Code"]
	,["Text","Section x+10","Code URL:"],["Edit","x+10 w300",""]
	,["Text","Section xm","Powered by GeekDude"]]})
	return
	34GuiEscape:
	34GuiClose:
	info:=window({get:34})
	settings.add("Pastebin",{user:info.ircname,public:info.public})
	Gui,34:Destroy
	return
	ptahk:
	info:=window({get:34}),code:=publish(1),desc:=info.desc?info.desc:"",username:=info.ircname?info.ircname:"annonymous"
	url:=ahkbin(code,username,desc,info.public)
	ControlSetText,Edit3,%url%,% win.h([34])
	settings.add("Pastebin",{user:username,public:info.public})
	return
}
;Thanks GeekDude
AhkBin(Txt, Author="GeekDude", Desc="Pasted by SciTE", Public=0){
	URL := "http://www.autohotkey.net/paste/"
	POST:= "MAX_FILE_SIZE=262144"
	.  "&jscheck="
	.  "&text=" . UriEncode(Txt)
	.  "&author=" . Author
	.  "&description=" . UriEncode(Desc)
	.  "&irc=" . (Public ? 100 : 0)
	.  "&submit=Paste"
	Pbin := ComObjCreate("WinHttp.WinHttpRequest.5.1")
	Pbin.Open("POST", URL)
	Pbin.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded")
	Pbin.Send(POST)
	RegExMatch(Pbin.ResponseText, "<title>Paste #(.*?)</title>", pb_url)
	return URL . pb_url1
}
UriEncode(Text) ; Uberi
{
	FormatInteger := A_FormatInteger, FoundPos := 0, SearchFor := "[^\w-.~% ]"
	SetFormat, IntegerFast, Hex
	StringReplace, Text, Text, `%, `%25, All
	While (FoundPos := RegExMatch(Text, SearchFor, Char, FoundPos + 1))
	StringReplace, Text, Text, %Char%, % "%" SubStr(0 SubStr(Asc(Char), 3), -1), All
	StringReplace, Text, Text, %A_Space%, +, All
	SetFormat, IntegerFast, %FormatInteger%
	Return Text
}
;End GeekDude Code
ftp(dir,upfile){
	all:=xml.easyatt(settings.ssn("//Ftp"))
	Progress,w500 h100,%file%,Uploading,File,% settings.ssn("//Style32/@Font").text
	settimer,Progress,200
	FTPCommandFile=%A_ScriptDir%\FTPCommands.txt
	FTPLogFile=%A_ScriptDir%\FTPLog.txt
	FileDelete %FTPCommandFile%  ; In case previous run was terminated prematurely.
	for a,b in upfile
	{
		if IsObject(b){
			for a,b in b
			splitpath,b,fn
			b:=a
		}
		else
		SplitPath,b,fn
		filename.="put "chr(34) b chr(34)" /" chr(34) dir "/" fn chr(34) "`n"
	}
	for a,b in all
	%a%:=b
	info=hash`necho`nopen %server%`n%username%`n%password%`nbinary`nmkdir %dir%`ncd %dir%`n%filename%ls -l`nquit
	fileappend,%info%,%ftpcommandfile%
	RunWait,%comspec% /c ftp.exe -s:"%FTPCommandFile%" >"%FTPLogFile%",,Hide
	FileDelete %FTPCommandFile%  ; Delete for security reasons.
	SetTimer,Progress,Off
	Progress,Off
	return
	Progress:
	FileRead,pro,%A_ScriptDir%\FTPLog.txt
	loop,Parse,pro,`n
	{
		if InStr(A_LoopField,"#")
		hash:=A_LoopField
		if InStr(A_LoopField,"put")
		file:=A_LoopField
		if InStr(file,"temp.upload")
		file:=chr(34) files.ssn("//*[@sc='" scin.2357 "']../@main").text chr(34)
	}
	RegExMatch(file,"U)" chr(34) "(.*)" chr(34),file)
	StringReplace,file,file,`",,All
	FileGetSize,kb,%file%
	RegExReplace(hash,"\#",0,count)
	percent:=(count*2048*100)/kb
	file:=file?file:"Logging in"
	pro(percent,file)
	return
}
pro(percent,file){
	Progress,%percent%,%file%,Uploading,File,Tahoma
}
remove_spaces_from_selected(){
	pos:=win.posinfo()
	text:=scin.textrange(pos.start,pos.end)
	text:=regexreplace(text," ")
	scin.2170(0,text)
}
filecheck(){
	fileinstall,commands.xml,commands.xml,1
	fileinstall,scilexer.dll,scilexer.dll,1
	ifexist scilexer.dll
	{
		FileGetVersion,sciver,scilexer.Dll
		;if sciver!=3.2.0.0
		;FileDelete,scilexer.dll
	}
	ifnotexist scilexer.dll
	{
		splashtexton,300,50,Downloading SciLexer.dll,Please wait
		urldownloadtofile,http://www.autohotkey.net/~maestrith/AHKStudio/SciLexer.dll,SciLexer.dll
	}
	if !fileexist("commands.xml"){
		splashtexton,300,50,Updating Commands File,Please wait
		urldownloadtofile,http://www.autohotkey.net/~maestrith/AHKStudio/commands.xml,commands.xml
		FileRead,com,commands.xml
		StringReplace,com,com,`n,`r`n,all
		FileDelete,commands.xml
		FileAppend,%com%,commands.xml
		Reload
	}
	if (comm.ssn("//Version/Date").text!=20121202182015&&comm.ssn("//Version/Date")){
		FileDelete,commands.xml
		Reload
	}
}
clean_position_data(){
	nodes:=positions.sn("/*/*")
	while,node:=nodes.item[a_index-1]
	ifnotexist,% ssn(node,"@main").text
	node.parentNode.removeChild(node),list.=ssn(node,"@main").text "`n"
	save()
	if list
	m("Information for files:`n" list "has been deleted.")
	else
	m("All position data is current")
}
edit_highlight_text(){
	window({num:14,title:"Edit Highlight Text",gui:[["Text","","Highlight lists are separated by a single space. (each word one space)"]
	,["ListView","w300 h500 AltSubmit ghighlight","List"]
	,["Edit","x+5 gupdatelist w495 h500"]]
	,GuiSize:{SysListView321:"h",Edit1:"wh"}})
	loop,7
	LV_Add("","Keyword List " A_Index)
	LV_Modify(1,"select Focus")
	return
	highlight:
	if A_GuiEvent not in normal,i
	return
	def:=[]
	Background:=settings.ssn("//Gui/Fonts/Style32/@Background").Text
	color:=settings.ssn("//Gui/Fonts/Style" LV_GetNext()+13 "/@Color").text
	dc:=Background=0xffffff?0:0xffffff
	color:=color?color:dc
	color:=RGB(Color)
	Gui,14:Default
	gui,14:font,c%color%
	gui,14:color,%background%,%background%
	winget,controllist,ControlList,% win.h([14])
	loop,Parse,ControlList,`n
	{
		guicontrol,+background%background%,%A_LoopField%
		gui,14:font,c%Color%,%font%
		guicontrol,font,%A_LoopField%
	}
	LV_GetText(list,LV_GetNext())
	key:=settings.ssn("//Gui/Fonts/Keywords/" clean(list))
	ControlSetText,Edit1,% key.text
	return
	updatelist:
	LV_GetText(list,LV_GetNext())
	ControlGetText,text,Edit1
	settings.add("Gui/Fonts/Keywords/" clean(list),"",text)
	return
	14GuiEscape:
	14GuiClose:
	keywords(98),sci.set()
	Gui,14:Destroy
	return
}
variables(){
	window({num:11,title:"Custom Variables",options:"+ToolWindow",gui:[["ListView","w200 h400","Variables"]
	,["Edit","w200"],["Button","w200 gvaradd Default","Add Variable"],["Button","w200 gvardel","Delete Selected"]]
	,GuiSize:{SysListView321:"wh",Edit1:"wy",Button1:"wy",Button2:"wy"}})
	vpop:
	Gui,11:Default
	nodes:=settings.sn("//Variables/*"),LV_Delete()
	while,var:=nodes.item[A_Index-1]
	LV_Add("",var.Text)
	ControlFocus,Edit1,% win.h([11])
	return
	varadd:
	Gui,11:Default
	ControlGetText,new,Edit1,% win.h([11])
	if !new:=clean(new,1)
	return
	if settings.ssn("//Variables/Variable[text()='" new "']")
	return m("Variable already exists")
	main:=settings.ssn("//Variables")?settings.ssn("//Variables"):settings.add("Variables")
	settings.add("Variable","",new,"","",main),settings.Transform(),keywords(98)
	ControlSetText,Edit1
	goto vpop
	return
	vardel:
	while,LV_GetNext(){
		LV_GetText(string,LV_GetNext())
		this:=settings.ssn("//Variable[text()='" string "']")
		this.parentnode.removechild(this)
		LV_Delete(LV_GetNext())
	}
	return
}
add_variable(){
	add_variable:
	variables()
	return
}
about(){
	copy=
	(
	License for Scintilla and SciTE
	
	Copyright 1998-2002 by Neil Hodgson <neilh@scintilla.org>
	
	All Rights Reserved 
	
	Permission to use, copy, modify, and distribute this software and its 
	documentation for any purpose and without fee is hereby granted, 
	provided that the above copyright notice appear in all copies and that 
	both that copyright notice and this permission notice appear in 
	supporting documentation. 
	
	NEIL HODGSON DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS 
	SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 
	AND FITNESS, IN NO EVENT SHALL NEIL HODGSON BE LIABLE FOR ANY 
	SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 
	WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, 
	WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER 
	TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE 
	OR PERFORMANCE OF THIS SOFTWARE. 
	
	AHK Pastebin code is provided by GeekDude.
	)
	window({num:3,title:"About",Gui:[["Edit","w700 center h500",RegExReplace(copy,"`t")],["Button","ggplus","Google+ Page"]]
	,GuiSize:{Edit1:"wh",Button1:"y"}})
	send,^{End}
	return
	gplus:
	Run,https://plus.google.com/115608377499733082736/posts
	return
}
show_file(){
	file:=files.ssn("//*[@sc='" scin.2357 "']/@file")
	f:=file.text
	file:="/select," chr(34) file.text chr(34)
	run explorer.exe %file%
}
show_functions(){
	file:=files.ssn("//*[@sc='" scin.2357 "']..")
	main:=sci.main()
	loop:=sn(file,"*")
	while,out:=ssn(loop.item[a_index-1],"@file"){
		code:=update(out.text)
		pos:=1
		while,pos:=RegExMatch(code,"OU)(.*)\(.*\).*{(.*)",fun,pos),pos:=pos+StrLen(fun.value(0)){
			if RegExMatch(ltrim(fun.value(1)),"[^a-zA-Z0-9_,]")
			continue
			if !fun.value(1)
			continue
			val:=Trim(RegExReplace(SubStr(fun.value(0),1,-1)," "))
			list.=val " "
		}
	}
	list:=trim(list)
	sort,list,UD%A_Space%
	sf:
	s:=scin,cpos:=s.2008,word:=s.textrange(s.2266(cpos,1),s.2267(cpos,1))
	s.2100(StrLen(word),list)
	while,s.2102{
		input,out,L1,{backspace}{Up}{Down}
		x:=ErrorLevel
		send,%out%
		if errorlevel = endkey:backspace
		{
			send,{BS}
			goto sf
		}
		key:=RegExReplace(x,"(EndKey:)")
		send,{%key%}
	}
}
restore(){
	window({num:4,title:"Restore file",Gui:[["ListView","x0 y0 w550 h480 altsubmit grestore","Backup"]
	,["Edit","x+0 w480 h480"]
	,["Button","x0 grestorefile Default","Restore selected file"]]
	,GuiSize:{SysListView321:"h",Edit1:"wh",Button1:"y"}})
	file:=files.ssn("//*[@sc='" scin.2357 "']/@file").text
	SplitPath,file,filename,dir
	Gui,4:Default
	loop,% dir "\backup\" filename,1,1
	{
		StringSplit,new,A_LoopFileDir,\
		last:=new0,d:=new%last%
		lv_add("",d)
	}
	LV_Modify(1,"select Focus")
	Restore:
	file:=files.ssn("//*[@sc='" scin.2357 "']/@file").text
	SplitPath,file,filename,dir
	LV_GetText(bdir,LV_GetNext())
	FileRead,contents,% dir "\backup\" bdir "\" filename
	ControlSetText,Edit1,%contents%
	return
	restorefile:
	ControlGetText,contents,Edit1
	Gui,4:Destroy
	scin.2181(0,contents)
	return
}
;http://www.autohotkey.com/community/viewtopic.php?t=63916
DynaRun(TempScript, pipename=""){ 
	static _:="uint" 
	@:=A_PtrSize ? "Ptr" : _ 
	If pipename = 
	name := "AHK" A_TickCount 
	Else 
	name := pipename 
	__PIPE_GA_ := DllCall("CreateNamedPipe","str","\\.\pipe\" name,_,2,_,0,_,255,_,0,_,0,@,0,@,0) 
	__PIPE_    := DllCall("CreateNamedPipe","str","\\.\pipe\" name,_,2,_,0,_,255,_,0,_,0,@,0,@,0) 
	if (__PIPE_=-1 or __PIPE_GA_=-1) 
	Return 0
	Run, %A_AhkPath% "\\.\pipe\%name%",,UseErrorLevel HIDE, PID
	If ErrorLevel 
	MsgBox, 262144, ERROR,% "Could not open file:`n" __AHK_EXE_ """\\.\pipe\" name """" 
	DllCall("ConnectNamedPipe",@,__PIPE_GA_,@,0) 
	DllCall("CloseHandle",@,__PIPE_GA_) 
	DllCall("ConnectNamedPipe",@,__PIPE_,@,0) 
	script := (A_IsUnicode ? chr(0xfeff) : (chr(239) . chr(187) . chr(191))) . TempScript 
	if !DllCall("WriteFile",@,__PIPE_,"str",script,_,(StrLen(script)+1)*(A_IsUnicode ? 2 : 1),_ "*",0,@,0) 
	Return A_LastError 
	DllCall("CloseHandle",@,__PIPE_) 
	Return PID 
}
run_selected_text(){
	text:=sci.getseltext()
	dynarun(text,"Test")	
}
delete_line(){
	scin.2338
}
copy_line(){
	scin.2469()
}
Quick_Find(x=""){
	static
	qs:=xml.easyatt(settings.ssn("//Quick_Search"))
	regex:=qs.regex?"Checked":"",sel:=qs.sel?"Checked":"",case:=qs.case?"Checked":""
	list:=window({num:17,title:"Quick Find",options:"-Resize +ToolWindow",Gui:[["Text","","Find:`t"],["Edit","gQf vout"]
	,["Text","","Replace:`t"],["Edit","vreplace"]
	,["Checkbox","vregex gQf " regex,"Regex"],["Checkbox","vcase gQf " case,"Case Sensitive"]
	,["Checkbox","gssel vsel " sel,"Search Within Selection"],["Button","gQfrepcur","Replace Current"]
	,["Button","gQfrep","Replace All"],["Button","gQfnf Default","Next Found"]]})
	Gui,17:show,AutoSize
	p:=win.posinfo(),s:=sci.lc
	os:=p.start+1,oe:=p.end,getpos()
	if (os!=oe)
	indic:={os:os,oe:oe}
	else
	indic:={os:0,oe:s.2006}
	return
	Qf:
	s:=sci.lc
	gosub format
	x:=q_f(find,indic)
	s.2574(0)
	return
	qfrepcur:
	gosub format
	main:=s.2575
	end:=s.2577(main),start:=s.2579(main)
	count:=s.2570
	otext:=s.textrange(start,end)
	before:=StrLen(otext)
	s.2571
	s.2160(start,end)
	rep:=RegExReplace(otext,find,replace,"",1,1)
	s.2170(0,rep)
	after:=strlen(rep)
	add:=after-before
	indic.oe:=indic.oe+add
	s.2571
	q_f(find,indic)
	main:=InStr(RegExReplace(otext,find,replace),otext)?main+1:main
	total:=s.2570
	main:=main=total?0:main
	s.2574(main)
	s.2169
	return
	Qfrep:
	gosub Format
	main:=s.2575
	end:=s.2577(main),start:=s.2579(main)
	otext:=s.textrange(start,end)
	rep:=RegExReplace(otext,find,replace,"",1,1)
	clip:=Clipboard
	Clipboard:=rep
	s.2179
	clipboard:=clip
	count:=s.2570
	add:=add*count
	goto 44GuiClose
	return
	ssel:
	gosub Format
	q_f(find,indic)
	s.2574(0)
	return
	Qfnf:
	s.2606
	s.2169
	return
	format:
	v:=window({get:17})
	case:=v.case,out:=v.out,regex:=v.regex,replace:=v.replace,sel:=v.sel
	settings.add("Quick_Search",v)
	indic["sel"]:=sel
	if strlen(out)=0
	{
		s.2571
		Exit
	}
	find:=""
	if !regex
	find:="O)(\Q" out "\E)"
	else if !RegExMatch(out,"[\(\)]")
	find:="O)(" out ")"
	else
	find:="O)" out
	if !case
	find:="i" find
	return
	44GuiEscape:
	44GuiClose:
	s.2505(indic.os,indic.oe) ;clear
	Gui,44:Destroy
	return
}
q_f(find="",sel=0){
	s:=sci.lc
	s.2571
	out:=s.gettext()
	if (sel.sel && Abs(sel.os-sel.oe)>1){
		found:=sel.os
		out:=SubStr(out,1,sel.oe)
	}
	found:=found?found:1
	while found:=RegExMatch(out,find,fo,found){
		if A_Index=1
		s.2160(fo.pos()-1,fo.pos()+strlen(fo.0)-1)
		else
		s.2573(fo.pos()+strlen(fo.0)-1,fo.pos()-1)
		found+=fo.len()
		total:=A_Index
	}
	if (total="")
	s.2571
	return total
}
sizemove(){
	win.getwinpos(x,y,w,h,win.h(A_Gui))
	if (x&&y&&w&&h&&A_Gui)
	settings.add("Gui/Position/Window" A_Gui,{x:x,y:y,w:w,h:h})
	if A_Gui=99
	ControlFocus,SysListView321,% win.h([8])
}
selabove(){
	selabove:
	opos:=scin.2585(0),oposa:=scin.2587(0),osw:=abs(opos-oposa),oline:=scin.2166(opos),oind:=opos-scin.2128(oline),line:=scin.2166(scin.2008)
	nextline:=InStr(A_ThisHotkey,"down")?line+1:line-1,length:=scin.2350(nextline)-2,nli:=scin.2128(nextline),nls:=scin.2167(nextline)
	if (InStr(A_ThisHotkey,"up")&&scin.2008=0)
	return
	opos:=scin.2585(0)
	ols:=scin.2167(opos)
	tsw:=(oind+osw)
	if (length<oind)
	scin.2573(nls+length,nls+length)
	else if (tsw<length)
	scin.2573(nli+oind+osw,nli+oind)
	else
	scin.2573(nls+length,nli+oind)
	return
}
select_matching_brace(){
	s:=sci.lc
	match:=s.2353(s.2008-1)
	if match!=-1
	s.2160(s.2008-1,s.2008),s.2573(match,match+1)
}
help(){
	run, http://code.google.com/p/ahk-studio/
}
create_comment_block(){
	pos:=win.posinfo(),s:=sci.lc,indent:=settings.ssn("//Indent").text
	cs:=s.2010(s.2008)
	s.2078
	if cs=10
	{
		start:=end:=s.2008
		while s.2010(start)=10,start--{
		}
		while s.2010(end)=10,end++{
		}
		startline:=s.2166(start),endline:=s.2166(end)
		ind:=s.2127(s.2166(start))
		add:=ind/indent
		start:=start-1>0?start-1:0
		s.2645(start,4+add)
		end:=end-(4+add)
		end:=s.2128(s.2166(end-1))
		s.2645(end-1,4+add)
		fix_indent()
		s.2079
		return
	}
	start:=s.2128(s.2166(pos.start)),end:=s.2136(s.2166(pos.end))
	s.2003(start,inline "/*`r`n")
	if (pos.start=pos.end)
	s.2003(end+4,"`r`n*/")
	else
	s.2003(end+4,"`r`n*/")
	s.2079
}
class Button{
	Color:=[],List:=[],wincall:=[]
	__New(Control){
		static window:=[]
		Button.colorize(Control)
		this.Control:=Control
		whwnd:=DllCall("GetParent","UPtr",Control,"UPtr")
		hdc:=DllCall("GetDC","UPtr",control,"UPtr")
		Button.list[whwnd,Control]:={hdc:hdc,win:whwnd}
		if !window[whwnd]{
			Button.win(Control)
			ControlGetFocus,Focus,% "ahk_id" whwnd
			ControlGet,hwn,hwnd,,%focus%,ahk_id%whwnd%
			if (hwn=control)
			Button.DrawFocusRect(Control,hdc)
			window[whwnd]:=1 
		}
	}
	Colors(c*){
		if c.1=""
		button.Color[0]:=[0xFF0000,0xFFFFFF,0],button.Color[1]:=[0x0000FF,0xFF0000,0] 
		else
		Button.Color[c.1]:=[c.2,c.3,c.4,c.5]
		window:=[],list:=Button.list
		for window in List
		for control in List[window]
		Button.colorize(Control)
	}
	Redraw(){
		window:=[],list:=Button.list
		for Window in List
		for Control in List[Window]
		Button.colorize(Control)
	}
	win(Control){ 
		this.hWindow:=DllCall("GetParent","UPtr",Control,"UPtr")
		this.pWindowCallback := RegisterCallback(this.WindowCallback,"Fast",6)
		Button.wincall[this.hwindow]:={this:this,call:this.pWindowCallback}
		DllCall("SetWindowSubclass","UPtr",this.hWindow,"UPtr",this.pWindowCallback,"UPtr",123456,"UPtr",this.hwindow)
	}
	WindowCallback(Message,wParam,lParam,SubclassID,Data){
		if (message=0x112&&wparam=0xF060)
		Gui,%data%:Destroy
		if message=0x2
		{
			Button.list.remove(data),Button.kill(data)
			WinGetTitle,title,ahk_id%data%
			if (title="Quick Find")
			if (win.posinfo().start=win.posinfo().end)
			setpos()
		}
		if message=0x2B 
		{
			MouseGetPos,,,,con,2
			Control:=NumGet(lParam+20)
			if (con=control&&GetKeyState("LButton","P")){
				Button.colorize(Control,1)
				KeyWait,LButton,U
				Button.colorize(Control)
			}
			sleep,0
			State:=NumGet(lParam+16,0,"UInt")
			hDC:=NumGet(lParam+20+A_PtrSize)
			if state=17
			Button.colorize(Control,1)
			if state=16
			Button.colorize(Control)
			if (state=0)
			Button.colorize(Control)
			else
			Button.DrawFocusRect(Control,hdc)
		}
		Return, DllCall("DefSubclassProc","UPtr",this,"UInt",Message,"UPtr",wParam,"UPtr",lParam,"UPtr") 
	}
	DrawFocusRect(Control,hdc){
		ControlGetPos,,,w,h,,ahk_id%Control%
		VarSetCapacity(rect,16)
		for offset,value in {0:2,4:2,8:w-2,12:h-2}
		NumPut(value,&rect,offset)
		DllCall("DrawFocusRect","UPtr",hdc,int,&rect)
	}
	kill(hWindow){
		pWindowCallback:=button.wincall[hWindow].call,t()
		DllCall("RemoveWindowSubclass","UPtr",hWindow,"UPtr",pWindowCallback,int,123456)
		DllCall("GlobalFree","UPtr",pWindowCallback,"UPtr")
	}
	colorize(hwnd,state=0){
		for a,b in {bc:1,pc:2,color:3}
		%a%:=Button.Color[state,b]
		WinSet,Style,+0xB,ahk_id %hwnd%
		sleep,0
		hDC := DllCall("GetDC",ptr,hwnd,ptr)
		hBrush:=DllCall("CreateSolidBrush",uint,bc,"UPtr")
		hpen:=DllCall("CreatePen",uint,0,"Int",1,uint,pc,"UPtr")
		hselpen:=DllCall("SelectObject","UPtr",hDc,"UPtr",hpen,"UPtr")
		hOriginalBrush:=DllCall("SelectObject","UPtr",hDc,"UPtr",hBrush,"UPtr")
		VarSetCapacity(rect,16,0),DllCall("GetClientRect",uint,hwnd,int,&rect)
		DllCall("Rectangle","UPtr",hDc,Int,NumGet(rect,0),Int,NumGet(rect,4),Int,NumGet(rect,8),Int,NumGet(rect,12))
		DllCall("SelectObject","UPtr",hDc,"UPtr",hOriginalBrush)
		DllCall("SelectObject","UPtr",hDc,"UPtr",hselpen)
		SendMessage,0x31,0,0,,ahk_id%hwnd%
		Font:=Errorlevel
		DllCall("SelectObject","UPtr",hDc,"UPtr",Font)
		DllCall("SetTextColor","UPtr",hDC,uint,Color)
		DllCall("SetBkMode","UPtr",hDC,Int,1)
		ControlGetText,Text,,ahk_id%hwnd% 
		DllCall("DrawText","UPtr",hdc,int,&text,int,StrLen(Text),int,&rect,int,0x1|0x20|0x4)
		DllCall("SelectObject","UPtr",hDc,"UPtr",Font)
	}
}
theme_button(){
	static
	static deft:=[]
	def:=colors("get"),cc:=RGB(def.color)
	Gui,44:Destroy
	Gui,44:+hwndhw +ToolWindow
	Gui,44:Color,% def.Background
	Gui,44:Default
	color:=["Border","Background","Text"]
	Gui,Add,Text,c%cc%,Click on either button to change the colors
	Gui,Add,Text,c%cc%,Normal Button
	for a,b in color
	{
		if A_Index=1
		Gui,Add,Button,hwndn%b% gtb%b% vn1,%b%
		else
		Gui,Add,Button,hwndn%b% gtb%b% x+10 vn%A_Index%,%b%
		deft[a_index]:=n%b%
	}
	Gui,Add,Text,xm c%cc%,Clicked Button
	for a,b in color
	{
		if A_Index=1
		Gui,Add,Button,hwndc%b% gtb%b% vc%a_index%,%b%
		else
		Gui,Add,Button,hwndc%b% gtb%b% x+10 vc%a_index%,%b%
		deft[a_index+3]:=c%b%
	}
	Gui,Show,,Button Editor
	for a,b in color
	n:="n" b,c:="c" b,button.colorize(%n%,0),button.colorize(%c%,1)
	return
	tbbackground:
	tbborder:
	tbtext:
	list:={tbbackground:1,tbborder:2,tbtext:3}
	state:=InStr(A_GuiControl,"n")?0:1
	ccc:=Button.Color[state,list[A_ThisLabel]]
	ccc:=dlg_color(ccc)
	Changestate(state,list[A_ThisLabel],ccc)
	for a,b in deft
	if A_Index<4
	Button.Colorize(b,0)
	else
	Button.Colorize(b,1)
	return
}
Changestate(state,change,new){
	Loop,3
	if A_Index=%change%
	c%A_Index%:=new
	else
	c%A_Index%:=button.color[state,a_index]
	button.colors(state,c1,c2,c3)
	set:=settings.add("Gui/Fonts/Button/State" state,{Border:c1,Background:c2,Text:c3})
}
code_vault(pop=0){
	if (pop){
		Menu,c,Add,Edit Vault,editvault
		l:=[]
		list:=settings.sn("//Code_Vault/*")
		while,node:=list.item[A_Index-1]
		l[node.nodename]:=1
		for a,b in l
		menu,c,Delete,%a%
		for a,b in l
		Menu,c,Add,%A%,insertcode
		return
	}
	window({num:18,title:"Code Vault",options:"+toolwindow",gui:[["ListView","AltSubmit vvault Sort w150 h300 gcvl","Code"],["Edit","x+10 h300 w300 vedit gcvup"]
	,["Text","Section xm","New Code Name"],["Edit","w150 x+10 ys-3"],["Button","gcvn xm Default","Add New Code"]
	,["Button","gcvd","Delete Selected Code"]]
	,GuiSize:{SysListView321:"h",Edit1:"wh",Button1:"y",Button2:"y",Static1:"y",Edit2:"y"}})
	list:=settings.sn("//Code_Vault/*")
	Gui,18:Default
	while,node:=list.item[A_Index-1]
	LV_Add("",node.nodename)
	LV_Modify(1,"Select Vis Focus")
	ControlGetPos,x,y,w,h,Edit1,% win.h([18])
	if list.length=0
	{
		ToolTip,Type the name for your code in the space below.`nAfter you name the code either`n`t1.Press the "Add New Code" button or`n`t2.Press enter`nThen enter the code here,x+5,y+10
		ControlFocus,Edit2,% win.h([18])
	}
	return
	cvn:
	ControlGetText,codename,Edit2,% win.h([18])
	if !codename
	return m("Please name the new code")
	if RegExMatch(SubStr(codename,1,1),"[0-9]")
	return m("Code name can not start with a number.")
	if settings.ssn("//Code_Vault/" codename)
	return m("Code name already exists.")
	LV_Modify(0,"-select"),LV_Add("select",codename),LV_Modify(LV_GetNext(),"Vis")
	settings.Add("Code_Vault/" codename)
	ControlSetText,Edit2,,% win.h([18])
	ControlFocus,Edit1,% win.h([18])
	code_vault(1),t()
	return
	cvl:
	LV_GetText(codename,LV_GetNext()),codename:=clean(codename,1)
	if A_GuiEvent in I,Normal
	ControlSetText,Edit1,% RegExReplace(settings.ssn("//Code_Vault/" codename).Text,"\n","`r`n"),% win.h([18])
	return
	cvup:
	LV_GetText(codename,LV_GetNext()),codename:=clean(codename,1)
	settings.ssn("//Code_Vault/" codename).text:=window({get:18}).edit,settings.save()
	return
	editvault:
	code_vault()
	return
	insertcode:
	text:=settings.ssn("//Code_Vault/" A_ThisMenuItem).text
	s:=sci.lc
	s.2003(s.2008,text)
	return
	cvd:
	Gui,18:Default
	while,next:=LV_GetNext(){
		LV_GetText(delete,next)
		remove:=settings.ssn("//Code_Vault/" delete)
		remove.parentnode.removechild(remove)
		menu,c,Delete,%delete%
		LV_Delete(next)
	}
	settings.save(),code_vault(1)
	return
}